您的位置:首页 > 其它

Linked List Cycle II

2013-12-16 19:23 148 查看
这篇文章讲得很清楚了。

http://fisherlei.blogspot.com/2013/11/leetcode-linked-list-cycle-ii-solution.html

/**
* 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 *fast = head, *slow = head;
while (fast != NULL && slow != NULL) {
fast = fast->next;
slow = slow->next;
if (fast != NULL)
fast = fast->next;
if (fast == slow)
break;
}
if (fast == NULL)
return NULL;
fast = head;
while (fast != slow) {
fast = fast->next;
slow = slow->next;
}
return fast;
}
};
http://oj.leetcode.com/problems/linked-list-cycle-ii/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: