forked from JFulgoni/Java-Practice
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLinkedListCycle.java
More file actions
78 lines (70 loc) · 1.73 KB
/
Copy pathLinkedListCycle.java
File metadata and controls
78 lines (70 loc) · 1.73 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
71
72
73
74
75
76
77
78
package john_test;
public class LinkedListCycle {
public LinkedListCycle(){
}
// This is a version of the tortoise and the hare problem
// We use one pointer that points to next, and one that points to next.next
public boolean findCycle(ListNodeX head){
ListNodeX tortoise;
ListNodeX hare;
if(head == null || head.next == null){
return false;
}
tortoise = head;
hare = head.next;
while(hare.next != null && hare != null){
tortoise = tortoise.next;
hare = hare.next.next;
if(tortoise == hare) break;
}
if(hare == null || hare.next == null){
return false;
}
return true;
}
// if there's a cycle, return the node
// else return null
public ListNodeX detectCycle(ListNodeX head){
ListNodeX tortoise;
ListNodeX hare;
if(head == null || head.next == null){
return null;
}
tortoise = head;
hare = head.next;
while(hare.next != null && hare != null){
tortoise = tortoise.next;
hare = hare.next.next;
if(tortoise == hare) break;
}
if(hare == null || hare.next == null){
return null;
}
//this is the part that differs from the boolean method
//returns the node where the cycle starts
tortoise = head;
while(tortoise != hare){
tortoise = tortoise.next;
hare = hare.next;
}
return tortoise;
}
// this code reverses a linked list from indexes m to n
public ListNodeX reverseLinkedList(ListNodeX head, int m, int n){
ListNodeX start = head;
//find the first start position
for(int i = 1; i < m; i++){
start = start.next;
}
ListNodeX temp;
ListNodeX end = start;
ListNodeX current = start.next;
for(int i = m; i < n; i++){
temp = current.next;
current.next = temp.next;
temp.next = start.next;
start.next = temp;
}
return head;
}
}