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 b39235b

Browse files
LC#141 check if cycle exists in given LinkedList
1 parent 3909e36 commit b39235b

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
package LinkedList;
2+
3+
public class LinkedListCycle141 {
4+
5+
public class ListNode {
6+
int val;
7+
ListNode next;
8+
9+
ListNode(int x) {
10+
val = x;
11+
next = null;
12+
}
13+
}
14+
15+
public boolean hasCycle(ListNode head) {
16+
17+
if (head == null || head.next == null)
18+
return false;
19+
20+
ListNode slow = head;
21+
ListNode fast = head;
22+
23+
while (fast.next != null || slow.next != null) {
24+
slow = slow.next;
25+
fast = fast.next.next;
26+
27+
if (slow == fast)
28+
return true;
29+
30+
if (fast == null)
31+
return false;
32+
33+
if (fast.next == null || slow.next == null)
34+
return false;
35+
}
36+
37+
return false;
38+
}
39+
40+
}

0 commit comments

Comments
(0)

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