Given a linked list, determine if it has a cycle in it.

Follow up:
Can you solve it without using extra space?

经典问题,判断一个单向链表是否有环,快慢指针,有相遇即有环。

/**
 * Definition for singly-linked list.
 * class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    public boolean hasCycle(ListNode head) {
        if (head == null)
            return false;
        ListNode fast = head, slow = head;
        int cnt = 0;
        while (true) {
            if (fast == null)
                return false;
            if (cnt > 0 && fast == slow)
                return true;
            slow = slow.next;
            fast = fast.next;
            if (slow == null || fast == null)
                return false;
            fast = fast.next;
            cnt ++;
        }
    }
}

 

相关文章:

  • 2022-02-11
  • 2021-09-02
  • 2021-12-05
  • 2022-01-06
  • 2021-09-22
  • 2021-12-16
猜你喜欢
  • 2021-07-08
  • 2022-02-02
  • 2022-01-05
  • 2021-10-04
  • 2022-01-09
  • 2021-04-23
  • 2021-08-08
  • 2022-03-08
相关资源
相似解决方案