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?
算法:
java:
/**
* Definition for singly-linked list.
* class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode detectCycle(ListNode head) {
if(null==head||null==head.next){
return null;
}
ListNode p,q,s,join=null;
p=head;
q=head;
s=head;
while(q!=null){
p=p.next;
q=q.next;
if(q!=null)
q=q.next;
else{
return null;
}
if(p==q){
join=q;
break;
}
}
if(join!=null){
while(join!=s){
join=join.next;
s=s.next;
}
return s;
}
return null;
}
}
c++:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *detectCycle(ListNode *head) {
if(!head||!head->next)
return NULL;
ListNode *p,*q,*s,*start;
p=head;
q=head;
s=NULL;
while(q){
q=q->next;
p=p->next;
if(q){
q=q->next;
}else{
return NULL;
}
if(p==q){
s=p;
break;
}
}
if(s){
start=head;
while(s!=start){
s=s->next;
start=start->next;
}
return start;
}
return NULL;
}
};