/**
* 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 faster = new ListNode(-1);
ListNode slower = new ListNode(-1);
faster = head;
if(faster == null)
return head;
slower = faster;
boolean isCycle = false;
while(faster != null && faster.next != null){
faster = faster.next.next;
slower = slower.next;
if(faster == slower){
isCycle = true;
break;
}
}
<span style="background-color: rgb(255, 255, 51);">while(isCycle){
if(slower == head)
return head;
head = head.next;
slower = slower.next;
}</span>
return null;
}
}
分析:不适用额外的空间,找圈的起点。圈的起点有什么特征呢?
一般节点都是只有一个指针(上一个节点的)指向它,圈的开头,除了上一个节点,还有一个尾巴节点指向它。这样圈的开头是唯一一个有两个指针指向它的节点。。。。。???这个解法待续~
剩下一个数学解法。快的走的路程始终是慢的2倍。当快的走了x+a+r时候,慢的走了x+a. 这里r=x+a;(x是list起点到圈起点的距离;a是圈起点到相遇点的距离;r是圈的周长)。解法就是找到相遇点之后,从相遇点同步同速度向前走,下一个碰头的地方就是圈起点。
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?