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

142. Linked List Cycle II

时间:2016-06-21 09:11:36      阅读:112      评论:0      收藏:0      [点我收藏+]

标签:

双指针,找到重合点,然后新一个指针从头出发,两个指针交汇的地方就是圈的起点

 1     public ListNode detectCycle(ListNode head) {
 2         if(head == null) {
 3             return null;
 4         }
 5         ListNode runner = head;
 6         ListNode walker = head;
 7         boolean hasCycle = false;
 8         while(runner.next != null && runner.next.next != null) {
 9             walker = walker.next;
10             runner = runner.next.next;
11             if(walker == runner) {
12                 hasCycle = true;
13                 break;
14             }
15         }
16         ListNode res = head;
17         if(hasCycle) {
18             while(walker != res) {
19                 res = res.next;
20                 walker = walker.next;
21             }
22             return res;
23         }
24         return null;
25     }

 

142. Linked List Cycle II

标签:

原文地址:http://www.cnblogs.com/warmland/p/5602361.html

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