您的位置:首页 > 其它

[leetcode][list][two pointers] Linked List Cycle II

2015-05-22 14:33 337 查看
题目:

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) {
//是否有环
if(NULL == head || NULL == head->next) return NULL;
ListNode *slow = head;
ListNode *fast = head->next;
while(fast && fast->next && slow != fast){
slow = slow->next;
fast = fast->next->next;
}
if(slow != fast) return NULL;//无环
//计算环中元素个数n
int cnt = 1;
slow = slow->next;
while(slow != fast){
++cnt;
slow = slow->next;
}
//前后指针,一个指针先走n部,然后两个指针同步向前,相遇点就是入口
ListNode *front = head;
ListNode *behind = head;
for(int i = 0; i < cnt; ++i) front = front->next;
while(front != behind){
front = front->next;
behind = behind->next;
}
return front;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: