首页 > 其他 > 详细

Linked List Cycle II

时间:2015-08-30 12:32:59      阅读:225      评论:0      收藏:0      [点我收藏+]

Given a linked list, return the node where the cycle begins. If there is no cycle, return null.

Note: Do not modify the linked list.

Follow up:
Can you solve it without using extra space?

 

 1 /**
 2  * Definition for singly-linked list.
 3  * struct ListNode {
 4  *     int val;
 5  *     ListNode *next;
 6  *     ListNode(int x) : val(x), next(NULL) {}
 7  * };
 8  */
 9 class Solution {
10 public:
11     ListNode *detectCycle(ListNode *head) {
12         /*
13         结题报告
14         首先要判断是否有环,详见Linked List Cycle
15         
16         假设当前慢指针已经走了s步,则快指针已经走了2s步,环的长度是r,链表长是L,从头指针到环处是a,从环到相遇处长度为x
17         则 2s = s + nr; 所以s= nr;
18         a + x = s; 所以 a+x = nr;
19         a+x = (n-1)r + r;
20         a+x = (n-1)r + L-a;
21         因此a = (n-1)r + L-a-x;
22         所以下一次头指针和slow指针必然会相遇,而且相遇处为环开始的节点
23         
24         */
25         
26         ListNode* fast = head;
27         ListNode* slow = head;
28         while(fast && fast->next){
29             fast = fast->next->next;
30             slow = slow->next;
31             if(fast == slow)
32                 break;
33         }
34         
35         if(fast== NULL || fast->next == NULL)
36             return NULL;
37         
38         ListNode* ptr = head;
39         while(ptr != slow){
40             ptr = ptr->next;
41             slow = slow->next;
42         }
43         return ptr;
44     }
45 };

 

Linked List Cycle II

原文:http://www.cnblogs.com/horizonice/p/4770562.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!