一 题目
Given a linked list, return the node where the cycle begins. If there is no cycle, return
Can you solve it without using extra space?
null
.
Note: Do not modify the linked list.
Follow up :Can you solve it without using extra space?
题意:判断一个链表中是否存在环,返回这个环的起点,如果不存在,请返回null。
问题分析:
1.首先如何判断一个链表中存在环呢?
定义两个指针,一个快指针fast,一个慢指针slow,快指针每次走两个节点,慢指针每次走一个节点。如果fast碰到null,说明此链表无环,如果slow == fast ,说明链表中存在环。因为在环形结构中,fast指针移动超越了slow指针一段距离,而这种情况,在无环的情况下是不存在的,就好比一条笔直的马路,跑的快的,永远在跑的慢的前面,如果是一个圈,那跑的快的一定会超越跑的慢的一圈,两圈,……,肯定会相遇。
2.如何找到环的起点
如图,X为链表的起点,Y为环的起点,而Z为fast和slow相遇的地方。
当slow走到Z时,他所走过的落成为a+b,而当fast走到Z时,他所走的距离为a+b+c+b,因为fast的速度是slow的两倍,所以有
2*(a+b) = a +b+ c + b,因此可以瑞出 a = c。
这个题的解题思路:
当fast和slow相遇时,此时重新定义一个指针从X位置开始移动,slow从Z开始移动,直到两个指针相遇,因为a = c,所以两个指针相遇的地方就是环开始的地方。
代码如下:
/**
* 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(fast!=null && fast.next!=null){
slow = slow.next;
fast = fast.next.next;
if(slow == fast){
ListNode slow2 = head;
while(slow !=slow2){
slow2 = slow2.next;
slow = slow.next;
}
return slow;
}
}
return null;
}
}