Skip to content

Commit e937012

Browse files
linked list cycle
1 parent 68bfad0 commit e937012

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed

EASY/src/easy/LinkedListCycle.java

+48
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
/**
2+
*
3+
*/
4+
package easy;
5+
6+
import java.util.HashMap;
7+
import java.util.Map;
8+
9+
import classes.ListNode;
10+
11+
/**
12+
* 141. Linked List Cycle QuestionEditorial Solution My Submissions
13+
Total Accepted: 120670
14+
Total Submissions: 331612
15+
Difficulty: Easy
16+
Given a linked list, determine if it has a cycle in it.
17+
18+
Follow up:
19+
Can you solve it without using extra space?
20+
*
21+
*/
22+
public class LinkedListCycle {
23+
24+
/**Cheers! Easily made this one AC'ed, after a while since I first solved this problem, just sort out the logic, pretty straightforward.*/
25+
public boolean hasCycle(ListNode head) {
26+
ListNode slow = head, fast = head;
27+
while(fast != null && fast.next != null){
28+
fast = fast.next.next;
29+
slow = slow.next;
30+
if(fast == slow) return true;
31+
}
32+
return false;
33+
}
34+
35+
/**Then, I found there's an editorial solution for this question, it uses a Hashtable to store visited nodes, if current node
36+
* is null, that means we reach the end of the list, then there must not be a cycle in the list.*/
37+
public boolean hasCycle_using_hashtable(ListNode head) {
38+
Map<ListNode, Boolean> visited = new HashMap();
39+
ListNode temp = head;
40+
while(temp != null){
41+
if(visited.containsKey(temp)) return true;
42+
visited.put(temp, true);
43+
temp = temp.next;
44+
}
45+
return false;
46+
}
47+
48+
}

0 commit comments

Comments
 (0)