forked from gouthampradhan/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
LinkedListCycle.java
59 lines (53 loc) · 1.32 KB
/
LinkedListCycle.java
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
package linked_list;
import java.util.HashSet;
import java.util.Set;
/**
* Created by gouthamvidyapradhan on 23/02/2017.
Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
*/
public class LinkedListCycle
{
private static Set<Integer> hashCode = new HashSet<>();
static class ListNode
{
int val;
ListNode next;
ListNode(int x)
{
val = x;
next = null;
}
}
/**
* Main method
* @param args
*/
public static void main(String[] args) throws Exception
{
ListNode node1 = new ListNode(1);
ListNode node2 = new ListNode(2);
ListNode node3 = new ListNode(3);
node1.next = node2;
node2.next = node3;
node3.next = node1;
System.out.println(new LinkedListCycle().hasCycle(node1));
}
public boolean hasCycle(ListNode head)
{
ListNode slow = head;
ListNode fast = head;
while(slow != null && fast != null)
{
slow = slow.next;
fast = fast.next;
if(fast != null)
fast = fast.next;
else break;
if(fast != null && slow != null)
if(fast.equals(slow)) return true;
}
return false;
}
}