-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathLeetCode-142-Linked-List-Cycle-II.java
More file actions
74 lines (59 loc) · 1.87 KB
/
LeetCode-142-Linked-List-Cycle-II.java
File metadata and controls
74 lines (59 loc) · 1.87 KB
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
/*
LeetCode: https://leetcode.com/problems/linked-list-cycle-ii/
LintCode: http://www.lintcode.com/problem/linked-list-cycle-ii/
JiuZhang: http://www.jiuzhang.com/solutions/linked-list-cycle-ii/
ProgramCreek: not find
http://fisherlei.blogspot.com/2013/11/leetcode-linked-list-cycle-ii-solution.html
Analysis:
1.Two Pointers
2.Two Pointers
*/
/**
* Definition for singly-linked list.
* class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
// 1.Two Pointers
public ListNode detectCycle(ListNode head) {
if (head == null || head.next == null) return null; // there is no cycle
ListNode slow = head, fast = head.next;
while (slow != fast) {
if (fast == null || fast.next == null) return null; // means there is no cycle
slow = slow.next;
fast = fast.next.next;
}
fast = head;
slow = slow.next; // we must let slow starts from the first one in the next round
while (fast != slow) {
slow = slow.next;
fast = fast.next;
}
return slow;
}
// 2.Two Pointers
public ListNode detectCycle(ListNode head) {
if (head == null) return null;
ListNode slow = head, fast = head;
while (fast.next != null && fast.next.next != null) {
slow = slow.next;
fast = fast.next.next;
if (slow == fast) {
System.out.println(slow.val);
break;
}
}
if (fast.next == null || fast.next.next == null) return null;
while (head != slow) {
head = head.next;
slow = slow.next;
}
return head;
}
}