题目
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.
* public class ListNode {
* public int val;
* public ListNode next;
* public ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode DetectCycle(ListNode head) {
if(head==null) return null;
ListNode slow = head;
ListNode fast=head;
while(true ){
slow=slow.next;
if(fast==null || fast.next==null) return null;
fast=fast.next.next;
if(slow==fast)
break;
}
//to get the begining point for cycle, so another while needs
slow=head;
while(slow!=fast){
slow=slow.next;
fast=fast.next;
}
return slow;
}
}
具体介绍说明,请参考地址:
http://www.jianshu.com/p/ce7f035daf74