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 4de6c5b

Browse files
Create List Cycle .java
1 parent 1f8e8cd commit 4de6c5b

File tree

1 file changed

+50
-0
lines changed

1 file changed

+50
-0
lines changed

‎LinkedList/List Cycle .java

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
/*
2+
Given a linked list, return the node where the cycle begins. If there is no cycle, return null.
3+
4+
Try solving it using constant additional space.
5+
6+
Example :
7+
8+
Input :
9+
10+
______
11+
| |
12+
\/ |
13+
1 -> 2 -> 3 -> 4
14+
15+
Return the node corresponding to node 3.
16+
*/
17+
18+
/**
19+
* Definition for singly-linked list.
20+
* class ListNode {
21+
* public int val;
22+
* public ListNode next;
23+
* ListNode(int x) { val = x; next = null; }
24+
* }
25+
*/
26+
public class Solution {
27+
public ListNode detectCycle(ListNode a) {
28+
ListNode slow = a;
29+
ListNode fast = a;
30+
31+
while (fast != null && fast.next != null) {
32+
slow = slow.next;
33+
fast = fast.next.next;
34+
35+
if (slow == fast) {
36+
break;
37+
}
38+
}
39+
40+
if (fast == null || fast.next == null) return null;
41+
42+
slow = a;
43+
while (slow != fast) {
44+
slow = slow.next;
45+
fast = fast.next;
46+
}
47+
48+
return slow;
49+
}
50+
}

0 commit comments

Comments
(0)

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