-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcycle.java
48 lines (46 loc) · 1.33 KB
/
cycle.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
public class cycle extends llpain {
public static boolean isCycle() {
Node slow = head;
Node fast = head;
while (fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
if (slow == fast)
return true;
}
return false;
}
public static void removeC() {
Node slow = head;
Node fast = head;
boolean cycle = false;
while (fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
if (fast == slow) {
cycle = true;
break;
}
}
if (cycle == false)
return;
slow = head; // find meet
Node prev = null; // last node
while (slow != fast) {
prev = fast;
slow = slow.next;
fast = fast.next;
}
prev.next = null; // remove cycle as last->next=null
}
public static void main(String[] args) {
head = new Node(1);
Node temp = new Node(2);
head.next = temp;
head.next.next = new Node(3);
head.next.next.next = temp;
System.out.println(isCycle());
removeC();
System.out.println(isCycle());
}
}