-
Notifications
You must be signed in to change notification settings - Fork 0
/
CycleNode.java
75 lines (67 loc) · 1.44 KB
/
CycleNode.java
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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
//Where you detect the LinkedList Cycle return that Node
/**
* 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) {
int length=0;
ListNode fast=head;
ListNode slow=head;
while(fast!=null && fast.next!=null)
{
fast=fast.next.next;
slow=slow.next;
if(fast==slow)
{
length=lengthCou(head);
break;
}
}
if(length==0)
{
return null;
}
ListNode f=head;
ListNode s=head;
while(length>0)
{
f=f.next;
length--;
}
while(f!=s)
{
f=f.next;
s=s.next;
}
return f;
}
private int lengthCou(ListNode head)
{
int length=0;
ListNode fast=head;
ListNode slow=head;
while(fast!=null && slow!=null)
{
fast=fast.next.next;
slow=slow.next;
if(fast==slow)
{
ListNode temp=slow;
do{
temp=temp.next;
length+=1;
}while(temp!=slow);
return length;
}
}
return 0;
}
}