导航
导航
文章目录
  1. 题目
  2. 翻译

LeetCode-142.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?

翻译

给出一个链表,返回换开始的节点。如果没有环,返回空。
跟进:你能不适用额外空间解决本题吗?

根据公式推导,可得出结论:
设立快慢指针,快指针每次走两步,慢指针每次走一步,若有环,当快慢指针相遇时,另设一个指针,从头部开始每次一步,慢指针也保持每次一步,那么第三个指针与慢指针最终会在换入口处相遇:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
/**
* 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, fast = head;
while (true) {
if (fast == null || fast.next == null) return null;
slow = slow.next;
fast = fast.next.next;
if (fast == slow) break;
}
ListNode cycle = head;
while (cycle != slow) {
cycle = cycle.next;
slow = slow.next;
}

return cycle;
}
}

参考:
http://www.tuicool.com/articles/3EZJbm