码迷,mamicode.com
首页 > 其他好文 > 详细

Linked List Cycle II (13)

时间:2014-11-13 00:20:11      阅读:281      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   io   color   sp   for   div   on   

 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? 

怎么求出有环链表环的开始位置呢?有没有o(n)解决方法?如果算法不清楚,根本无法搞啊!

判断有环链表的问题在问题Linked List Cycle中已经解决了,即通过设置快慢指针的方式,快指针每次走两步,慢指针每次走一步,如果链表有环的话,快慢指针一定会重合,我们就从这一时刻开始说起!

无图无真相,上图!

bubuko.com,布布扣

设最后快慢指针相遇的位置为图示圆点的位置,设起点到环起点距离为x,圆点将环分为图示y,z两部分。设慢指针在相遇前走了s1,快指针在相遇前走了s2.易知有图上公式成立,得出x=y.

所以,在相遇时,将fast指针移至head位置,设置fast和slow指针每次向前走一步,最终两个指针会在环的起点处相遇。思路弄清楚了!

上代码!

 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         ListNode *fast,*slow;
13         fast=slow=head;
14         while(fast&&fast->next){
15             slow=slow->next;
16             fast=fast->next->next;
17             if(fast==slow)
18                 return true;
19         }
20         return false;
21     }
22 };

 

Linked List Cycle II (13)

标签:style   blog   http   io   color   sp   for   div   on   

原文地址:http://www.cnblogs.com/zhoudayang/p/4093765.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!