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.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
bool hasCycle(ListNode *head) {
if(!head) return false;
ListNode * p = head;
ListNode * q = head;
while(q->next != NULL && q->next->next != NULL){
p = p->next;
q = q->next->next;
if(q == p)
return true;
}
return false;
}
};
- Use two pointers, walker and runner.
- walker moves step by step. runner moves two steps at time.
- if the Linked List has a cycle walker and runner will meet at some
point.
链表循环检测
本文介绍了一种使用快慢指针的方法来判断链表中是否存在循环。通过两个速度不同的指针,一个每次移动一步,另一个每次移动两步,在存在循环的情况下这两个指针最终会在循环内相遇。
580

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



