LeetCode|Linked List Cycle II
阿新 • • 發佈:2019-02-08
題目
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?
思路
本來我傻傻的用 Linked List Cycle 的方法來做,以為找到了節點就意味著這個點就是環的開始。但是,結果報了個錯
Input: | {3,2,0,-4}, tail connects to node index 1 |
Output: | tail connects to node index 3 |
Expected: | tail connects to node index 1 |
於是換了另一個思路.
我們假設slow走了n步,而fast走了2n步.在環的某個點相遇(假設點D).那麼,想一下.如果讓fast不動,讓slow在走n步,slow是不是剛好又回到了這個相遇點(D)?(因為fast走了2n步到達這個地方).那麼此時,如果讓fast也從連結串列的開頭走,走n步.那麼fast和slow必定會在D相遇.但是,這之前,它們就會提前相遇,而相遇點就是環入口!
程式碼
/** * Definition for singly-linked list. * class ListNode { * int val; * ListNode next; * ListNode(int x) { * val = x; * next = null; * } * } */ public class Solution { public ListNode detectCycle(ListNode head) { ListNode node = null; if(head == null) return node; ListNode quick = head; ListNode slow = head; boolean tag = false; while(quick!=null &&quick.next != null) { quick = quick.next; quick = quick.next; slow = slow.next; if(quick == slow) { tag = true; break; } } if( tag == false) { return node; } else { quick = head; while( true) { if( quick == slow) { return quick; } else { quick = quick.next; slow = slow.next; } } } } }