Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
Analysis:
two pointers.One pointer is slow (1 step a time)
One pointer is fast (2 steps a time)
If there is a cycle, the two pointers will eventually meet (equal).
java
public boolean hasCycle(ListNode head){
if(head == null || head.next == null) return false;
ListNode p1 = head;
ListNode p2 = head;
while(p1!=null){
p1 = p1.next;
if(p2.next!=null)
p2 = p2.next.next;
else
return false;
if(p1 == p2)
return true;
}
return false;
}c++
bool hasCycle(ListNode *head) {
if(head == NULL)
return false;
ListNode *slow = head;
ListNode *fast = head->next;
while(slow !=NULL && fast !=NULL){
if(slow == fast)
return true;
slow = slow->next;
fast = fast->next;
if(fast ==NULL)
return false;
fast = fast->next;
}
return false;
}

本文介绍了一种使用快慢指针的方法来判断链表中是否存在循环。通过一个快速指针(每次移动两步)和一个慢速指针(每次移动一步),如果链表存在循环,则这两个指针最终会相遇。
1171

被折叠的 条评论
为什么被折叠?



