Question:

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

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

 

Analysis:

思路一:快慢指针法。前面用到过快慢指针寻找链表的中间节点。若快慢指针会相遇,则说明有环;否则快指针遇到null,则说明无环。

 

Answer:(Beats 100% java submission~)

public class Solution {
    public boolean hasCycle(ListNode head) {
        if(head == null)
            return false;
        ListNode fast = head, slow = head;
        while(fast.next != null || fast == null) {
            if(fast.next == null || fast == null || fast.next.next == null)
                return false;
            slow = slow.next;
            fast = fast.next.next;
            if(slow == fast)
                return true;
        }
        return false;
    }
}

 

相关文章:

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