Leetcode: Linked List Cycle II
2014-01-29 00:39
447 查看
http://oj.leetcode.com/problems/linked-list-cycle-ii/
参考了http://blog.csdn.net/whuwangyi/article/details/14103993
/**
* 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==NULL) return NULL;
ListNode* fastHead=head;
ListNode* slowHead=head;
// get the first meeting point
while(true){
slowHead=slowHead->next;
fastHead=fastHead->next;
if(fastHead==NULL) return NULL;
fastHead=fastHead->next;
if(fastHead==NULL) return NULL;
if(fastHead==slowHead) break;
}
// get the length of the cycle
int cnt=1;
slowHead=slowHead->next;
while(slowHead!=fastHead){
slowHead=slowHead->next;
cnt++;
}
// start from the head and make the fastHead ahead of slowHead by cnt nodes
fastHead=slowHead=head;
while(cnt!=0){
fastHead=fastHead->next;
cnt--;
}
while(fastHead!=slowHead){
fastHead=fastHead->next;
slowHead=slowHead->next;
}
return fastHead;
}
};
参考了http://blog.csdn.net/whuwangyi/article/details/14103993
/**
* 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==NULL) return NULL;
ListNode* fastHead=head;
ListNode* slowHead=head;
// get the first meeting point
while(true){
slowHead=slowHead->next;
fastHead=fastHead->next;
if(fastHead==NULL) return NULL;
fastHead=fastHead->next;
if(fastHead==NULL) return NULL;
if(fastHead==slowHead) break;
}
// get the length of the cycle
int cnt=1;
slowHead=slowHead->next;
while(slowHead!=fastHead){
slowHead=slowHead->next;
cnt++;
}
// start from the head and make the fastHead ahead of slowHead by cnt nodes
fastHead=slowHead=head;
while(cnt!=0){
fastHead=fastHead->next;
cnt--;
}
while(fastHead!=slowHead){
fastHead=fastHead->next;
slowHead=slowHead->next;
}
return fastHead;
}
};
相关文章推荐
- [LeetCode] Linked List Cycle II
- LeetCode---Linked List Cycle II
- 【leetcode】Linked List Cycle II (middle)
- LeetCode 141 Linked List Cycle和142 Linked List Cycle II
- 【题解】【链表】【Leetcode】Linked List Cycle II
- LeetCode Linked List Cycle II
- Leetcode Linked List Cycle II
- 【LeetCode从零单刷】Linked List Cycle I & II
- LeetCode Linked List Cycle II
- [LeetCode]Linked List Cycle II
- Leetcode之Linked List Cycle II 问题
- Leetcode: linked-list-cycle-ii
- [LeetCode#142]Linked List Cycle II
- [leetCode]Linked List Cycle I+II
- LeetCode:Linked List Cycle II
- leetcode Linked List Cycle II python
- LeetCode Linked List Cycle II
- LeetCode题解——Linked List Cycle II
- [leetcode] Linked List Cycle II
- leetcode--Linked List Cycle II