-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLeetCode0141.java
More file actions
70 lines (63 loc) · 1.98 KB
/
Copy pathLeetCode0141.java
File metadata and controls
70 lines (63 loc) · 1.98 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
/* Linked List Cycle
* Input: head = [3,2,0,-4], pos = 1
* 3->2->0->-4
* | |
* --------
* Output: true
* Explanation: There is a cycle in the linked list, where the tail connects to the 1st node (0-indexed).
* */
import java.util.HashSet;
import java.util.Set;
public class LeetCode0141 {
public static void main(String args[]){
int[] input = new int[]{3, 2, 0, -4};
ListNode l1 = buildLoopListNode(input, 1);
System.out.println(hasCycle(l1));
}
public static boolean hasCycle(ListNode head) {
// Use hash map
/*if (head == null)
return false;
Set<ListNode> visited = new HashSet<>();
while (head != null){
if (visited.contains(head))
return true;
else
visited.add(head);
head = head.next;
}
return false;*/
// Use two pointers
if (head == null)
return false;
ListNode slow = head;
ListNode fast = head.next;
while (slow != fast){
if (fast == null || fast.next == null)
return false;
slow = slow.next;
fast = fast.next.next;
}
return true;
}
private static ListNode buildLoopListNode(int[] input, int pos) {
ListNode first = null, last = null, newNode, loop = null;
if (input.length > 0) {
for (int i = 0; i < input.length; i++) {
newNode = new ListNode(input[i]);
newNode.next = null;
if (first == null) {
first = newNode;
last = newNode;
} else {
last.next = newNode;
last = newNode;
}
}
for (int i = 0; i < pos; i++)
loop = first.next;
last.next = loop;
}
return first;
}
}