1. 程式人生 > >142. Linked List Cycle II

142. Linked List Cycle II

fast pro http spa node itl fad class 起點

題目:

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?

Hide Tags Linked List Two Pointers

鏈接: http://leetcode.com/problems/linked-list-cycle-ii/

6/11/2017

註意

第11,12行沒有放在第7行是為了排除第一次最開始slow, fast都在head的情況,但是也不應該在第7行判斷是否2者當時是head,有可能環的起點就是head

 1 public class Solution {
 2     public ListNode detectCycle(ListNode head) {
 3         if (head == null) {
 4             return head;
 5         }
 6         ListNode slow = head, fast = head;
 7         while (fast != null && fast.next != null) {
 8             slow = slow.next;
 9             fast = fast.next;
10 fast = fast.next; 11 if (slow == fast) { 12 break; 13 } 14 } 15 if (fast == null || fast.next == null) { 16 return null; 17 } 18 fast = head; 19 while (fast != slow) { 20 fast = fast.next;
21 slow = slow.next; 22 } 23 return fast; 24 } 25 }

這道題應該是記下來的,但是分析不會

更多討論

https://discuss.leetcode.com/category/150/linked-list-cycle-ii

142. Linked List Cycle II