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?
Java:
1. 这个分析的比较清楚,还有图,代码很好懂,但不是很严谨,
http://www.cnblogs.com/hiddenfox/p/3408931.html
/**
* 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 slow=head;
ListNode fast=head;
while(true)
{
if(fast==null||fast.next==null)
{
return null;
}
slow=slow.next;
fast=fast.next.next;
if(fast==slow){
break;
}
}
slow=head;
while(slow!=fast)
{
slow=slow.next;
fast=fast.next;
}
return slow;
}
}
2.
改动了一点,http://blog.youkuaiyun.com/u010500263/article/details/18286547
public class Solution {
public ListNode detectCycle(ListNode head) {
if(head == null || head.next == null) return null;
ListNode slow = head;
ListNode fast = head;
// find out the meeting point
while (fast != null && fast.next != null){
fast = fast.next.next;
slow = slow.next;
if(fast == slow) break;
}
if (fast == null || fast.next == null) return null;
// (circle must exist) find out the start point
ListNode start1 = head;
ListNode start2 = fast;
while (start1 != start2){
start1 = start1.next;
start2 = start2.next;
}
return start1;
}
}
3.
http://blog.youkuaiyun.com/fightforyourdream/article/details/14639657
public class Solution {
public ListNode detectCycle(ListNode head) {
if(head == null || head.next ==null){
return null;
}
ListNode slow = head;
ListNode fast = head;
// 找到第一次相遇点
while(fast!=null && fast.next!=null && slow!=null){
slow = slow.next;
fast = fast.next.next;
if(slow == fast){ // 相遇
break;
}
}
// 检查是否因为有环退出或是因为碰到null而退出
if(slow==null || fast==null || fast.next==null){
return null;
}
// 把慢指针移到链表头,然后保持快慢指针同样的速度移动
// 再次相遇时即为环的入口
slow = head;
while(slow != fast){
slow = slow.next;
fast = fast.next;
}
// 现在快慢指针都指向环的入口
return slow;
}
}