- Notifications
You must be signed in to change notification settings - Fork 366
/
Copy pathLinkedListCycle.java
41 lines (29 loc) · 1.05 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
/*
LEETCODE QUESTION : 141. Linked List Cycle
=> There is a cycle in a linked list if there is some node in the list that can be reached again by continuously following the next pointer. Internally,
pos is used to denote the index of the node that tail's next pointer is connected to. Note that pos is not passed as a parameter.
Return true if there is a cycle in the linked list. Otherwise, return false.
*/
// * Definition for singly-linked list.
publicclassListNode {
intval;
ListNodenext;
ListNode() {
}
ListNode(intval) {
this.val = val;
}
publicclassLinked_List_Cycle {
publicbooleanhasCycle(ListNodehead) {
ListNodefast = head;
ListNodeslow = head;
//for iteration
while(fast!=null && fast.next!=null){
fast=fast.next.next; //iterate 2 times
slow = slow.next; //iterate 1 time
if(slow== fast)
returntrue;
}
returnfalse;
}
}