文章目录

LeetCode地址:https://leetcode.com/problems/linked-list-cycle-ii/

Problem:
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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
/**
* 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 cycleStart=null,
singleStepNode=null,
doubleStepNode=null;
boolean isCycle=false;

if(head==null)
return cycleStart;

singleStepNode =head;
doubleStepNode=head;

while(singleStepNode!=null && doubleStepNode!=null && doubleStepNode.next!=null)
{
singleStepNode=singleStepNode.next;

doubleStepNode=doubleStepNode.next.next;

if(singleStepNode==doubleStepNode)
{
isCycle=true;
break;
}
}

if(isCycle)
{
singleStepNode=head;
while(singleStepNode != doubleStepNode)
{
singleStepNode=singleStepNode.next;
doubleStepNode=doubleStepNode.next;
}

cycleStart=singleStepNode;
}

return cycleStart;
}
}

本作品采用[知识共享署名-非商业性使用-相同方式共享 2.5]中国大陆许可协议进行许可,我的博客欢迎复制共享,但在同时,希望保留我的署名权kubiCode,并且,不得用于商业用途。如您有任何疑问或者授权方面的协商,请给我留言

文章目录