Java for LeetCode 141 Linked List Cycle

时间:2023-03-09 19:59:26
Java for LeetCode 141 Linked List Cycle

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

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

解题思路:

由于不让用extra space,所以用一个快指针和一个慢指针,快指针一次移动两步,慢指针一次移动一步,只要快指针赶上慢指针证明纯在loop,JAVA实现如下:

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