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 public ListNode detectCycle(ListNode head) { 14 if (head == null || head.next == null) { 15 return null; 16 } 17 ListNode fast = head.next; 18 ListNode slow = head; 19 while (fast != null && fast.next != null) { 20 if (slow == fast) { 21 break; 22 } 23 slow = slow.next; 24 fast = fast.next.next; 25 } 26 if (fast == null || fast.next == null) { 27 return null; 28 } 29 //注意是head != slow.next 30 while (head != slow.next) { 31 head = head.next; 32 slow = slow.next; 33 } 34 return head; 35 } 36 }

浙公网安备 33010602011771号