Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit c804312

Browse files
LC#142 find first meet point in linkedlist cycle - medium problem
1 parent b39235b commit c804312

File tree

1 file changed

+50
-0
lines changed

1 file changed

+50
-0
lines changed
Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
package LinkedList;
2+
3+
public class LinkedListCycleII142 {
4+
5+
class ListNode {
6+
int val;
7+
ListNode next;
8+
9+
ListNode(int x) {
10+
val = x;
11+
next = null;
12+
}
13+
}
14+
15+
public ListNode detectCycle(ListNode head) {
16+
17+
if (head == null || head.next == null)
18+
return null;
19+
20+
ListNode ptr1 = head;
21+
ListNode ptr2 = detectCycle1(head);
22+
23+
if (ptr2 == null)
24+
return null;
25+
26+
while (ptr1 != ptr2) {
27+
ptr1 = ptr1.next;
28+
ptr2 = ptr2.next;
29+
}
30+
31+
return ptr1 == ptr2 ? ptr1 : null;
32+
}
33+
34+
private static ListNode detectCycle1(ListNode head) {
35+
if (head == null || head.next == null)
36+
return null;
37+
38+
ListNode slow = head, fast = head;
39+
40+
while (fast != null && fast.next != null) {
41+
slow = slow.next;
42+
fast = fast.next.next;
43+
44+
if (slow == fast) {
45+
return fast;
46+
}
47+
}
48+
return null;
49+
}
50+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /