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==NULL)return false;
ListNode *q=head,*p=head;
while(q){
q=q->next;
if(q)q=q->next;
p=p->next;
if(p==q)break;
}
if(q)return true;
else return false;
}
};
II
Given a linked list, return the node where the cycle begins. If there is no cycle, return null
.
Follow up:
Can you solve it without using extra space?
class Solution {
public:
ListNode *detectCycle(ListNode *head) {
if(head==NULL)return NULL;
ListNode *p=head,*q=head;
while(q){
q=q->next;
if(q)q=q->next;
p=p->next;
if(p==q)break;
}
if(q==NULL)return NULL;
q=head;
while(q!=p){
q=q->next;
p=p->next;
}
return q;
}
};