Skip to content

Commit e2977c4

Browse files
committed
feat : liked-list-cycle
1 parent 6ebd1db commit e2977c4

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed

linked-list-cycle/ekgns33.java

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
/**
2+
* Definition for singly-linked list.
3+
* class ListNode {
4+
* int val;
5+
* ListNode next;
6+
* ListNode(int x) {
7+
* val = x;
8+
* next = null;
9+
* }
10+
* }
11+
*/
12+
13+
/*
14+
* input : singly linked list and head node
15+
* output : return true if list has cycle
16+
*
17+
* solution : tortoise and hare algorithm
18+
* with two pointer (slow and fast)
19+
* tc : O(n)
20+
* sc : O(1)
21+
*
22+
* */
23+
public class Solution {
24+
public boolean hasCycle(ListNode head) {
25+
if(head == null) return false;
26+
ListNode slow = head;
27+
ListNode fast = head;
28+
while(fast.next != null && fast.next.next != null) {
29+
slow = slow.next;
30+
fast = fast.next.next;
31+
if(fast == slow) return true;
32+
}
33+
return false;
34+
}
35+
}

0 commit comments

Comments
 (0)