[Leetcode]142. Linked List Cycle II
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.
思路:我的想法是先用快慢指针判断是否有环,如果有环的话,找出快慢指针相遇的那个点。
然后让一个指针一直在那个环里循环,而另一个新指针从头节点开始走,返回他们相遇的那个点;
1 /** 2 * Definition for singly-linked list. 3 * class ListNode { 4 * int val; 5 * ListNode next; 6 * ListNode(int x) { 7 * val = x; 8 * next = null; 9 * } 10 * } 11 */ 12 public class Solution { 13 private ListNode cur; 14 public ListNode detectCycle(ListNode head) { 15 if (head==null||head.next==null) 16 return null; 17 ListNode p = head,q = head; 18 while (q!=null){ 19 q = q.next; 20 if (q==null) 21 return null; 22 q = q.next; 23 p = p.next; 24 if (p==q) 25 break; 26 } 27 if (q==null) 28 return null; 29 else 30 helper(head,p,q.next); 31 return cur; 32 } 33 private void helper(ListNode head,ListNode p,ListNode q){ 34 if (p==head){ 35 cur = head; 36 } 37 if (cur==null){ 38 while(q!=p){ 39 p = p.next; 40 if (p==head) 41 cur = head; 42 } 43 helper(head.next,p,q.next); 44 } 45 } 46 }