142. Linked List Cycle II

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

 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     }

 

posted @ 2016-06-21 06:49  warmland  阅读(112)  评论(0编辑  收藏  举报