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.
Follow up:
Can you solve it without using extra space?
/** * 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 fast = head; //fast pointer moves two steps forward ListNode slow = head; //slow pointer moves one step forward while(fast != null && fast.next != null){ slow = slow.next; fast = fast.next.next; if(slow == fast){ slow = head; while(slow != fast){ slow = slow.next; fast = fast.next; } return slow; } } return null; } }
Reference:
1. http://bangbingsyb.blogspot.com/2014/11/leetcode-linked-list-cycle-i-ii.html
2. https://leetcode.com/discuss/65724/concise-java-solution-based-on-slow-fast-pointers
原文:http://www.cnblogs.com/anne-vista/p/4960877.html