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

142. Linked List Cycle II

时间:2017-10-16 23:29:46      阅读:228      评论:0      收藏:0      [点我收藏+]

标签:bsp   head   cycle   col   can   lower   nod   node   return   

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?

 

头结点到cycle begins的点 距离是A, cycle begins的点 到快慢结点相遇的 点的距离是B

A+B+N = 2*(A+B)

A+B = N

所以 快慢指针相遇后,从头结点开始再跑一个慢指针,直到2个慢的相遇,相遇的点就是cycle begin

 

 

 1 public class Solution {
 2     public ListNode detectCycle(ListNode head) {
 3         ListNode faster = head;
 4         ListNode slower = head;
 5         
 6         while(faster !=null && faster.next != null){
 7             faster = faster.next.next;
 8             slower = slower.next;
 9         
10             if(faster == slower){
11                 ListNode slower2 = head;
12                 while(slower != slower2){
13                     slower = slower.next;
14                     slower2 = slower2.next;
15                 }
16                 return slower;
17             }
18        }
19        return null;
20         
21     }
22 }

 

142. Linked List Cycle II

标签:bsp   head   cycle   col   can   lower   nod   node   return   

原文地址:http://www.cnblogs.com/zle1992/p/7679160.html

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