Linked List Cycle II
问题:
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?
思路:
相遇之后 ,一个指针从头开始,另外一个指针从相遇点开始,再次相遇的时候就是环的开始处
我的代码:
public class Solution { public ListNode detectCycle(ListNode head) { if(head == null || head.next == null) return null; ListNode slow = head, fast = head; do { if(fast == null || fast.next == null) return null; slow = slow.next; fast = fast.next.next; }while(slow != fast); slow = head; while(slow != fast) { slow = slow.next; fast = fast.next; } return slow; } }
学习之处:
原文:http://www.cnblogs.com/sunshisonghit/p/4322242.html