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?
剑指offer里也有同样的题,分为三步找到环形链表的入口结点,这里就只记录这次自己写的代码,具体的思路分析见链表中环的入口结点
代码:
/**
* 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 *meetingnode = meetingcycle(head);
if(meetingnode==NULL)
return NULL;
//计算环内节点个数
int count = 1;
ListNode *cur = meetingnode;
while(cur!=NULL){
cur = cur->next;
if(cur==meetingnode)
break;
count++;//这里要注意break和count++的顺序问题
}
//寻找入口点
ListNode *slow = head;
ListNode *fast = head;
for(int i = 0;i < count;++i){
fast = fast->next;
}
while(slow!=fast){
slow = slow->next;
fast = fast->next;
}
return slow;
}
//找到一个环内节点
ListNode *meetingcycle(ListNode *head){
if(head==NULL || head->next==NULL)
return NULL;
ListNode *slow = head;
ListNode *fast = head->next;
while(slow!=NULL && fast!=NULL){
if(slow==fast)
return slow;
slow = slow->next;
fast = fast->next;
if(fast!=NULL)
fast = fast->next;
}
return NULL;
}
};