problem:
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?
方法:
求链表中是否有环的扩展。
用快慢指针法判定是否存在环,若存在求出环的长度,用两个指针,间隔环的长度向前同步移动,
当指针值相等时,他们所指向的节点即为环的开始节点。
代码:
/**
* 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) {
ListNode *slow, *fast;
if(!head){
return NULL;
}
slow = head;
fast = head->next;
while(true){
if((!fast) || (!fast->next)){
return NULL;
}else if(fast == slow){
break;
}
fast = fast->next->next;
slow = slow->next;
}
int len = 1;
for(ListNode *temp = slow; temp->next != slow; temp = temp->next){
len++;
}
ListNode *p, *q;
p = q = head;
for(int i = 0; i < len; i++){
q = q->next;
}
while(p != q){
p = p->next;
q = q->next;
}
return p;
}
};