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 fb52881

Browse files
updates linked list cycle
1 parent c451a76 commit fb52881

File tree

1 file changed

+12
-13
lines changed

1 file changed

+12
-13
lines changed

‎src/LinkedListCycle.java‎

Lines changed: 12 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,26 +1,25 @@
1-
importjava.util.HashSet;
2-
importjava.util.Set;
1+
// T: O(n)
2+
// S: O(1)
33

44
public class LinkedListCycle {
5-
static class ListNode {
5+
privatestatic class ListNode {
66
int val;
77
ListNode next;
88
ListNode(int x) {
9-
val = x;
10-
next = null;
9+
val = x;
10+
next = null;
1111
}
1212
}
1313

1414
public boolean hasCycle(ListNode head) {
15-
Set<ListNode> nodes = new HashSet<>();
16-
while (head != null) {
17-
if (nodes.contains(head)) {
18-
return true;
19-
} else {
20-
nodes.add(head);
21-
}
22-
head = head.next;
15+
if (head == null) return false;
16+
17+
for (ListNode slow = head, fast = head.next; fast != null && fast.next != null ; ) {
18+
if (slow == fast) return true;
19+
slow = slow.next;
20+
fast = fast.next.next;
2321
}
22+
2423
return false;
2524
}
2625
}

0 commit comments

Comments
(0)

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