-
Notifications
You must be signed in to change notification settings - Fork 30
/
Copy pathdetect_remove_cycle_in_linkedlist.java
85 lines (72 loc) · 2.23 KB
/
detect_remove_cycle_in_linkedlist.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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
package Linkedlist;
public class detect_remove_cycle_in_linkedlist {
Node head;
static class Node
{
Node head;
int data;
Node next;
Node(int data)
{
this.data=data;
this.next=null;
}
}
public Node detect(Node head)
{
Node meetpoint=meetnode(head);
Node firstnode=head;
while(firstnode!=meetpoint)
{
meetpoint=meetpoint.next;
firstnode=firstnode.next;
}
return firstnode;
}
public Node meetnode(Node head) {
Node slow = head;
Node fast = head;
while (fast.next != null && fast != null) {
slow = slow.next;
fast = fast.next.next;
if (slow == fast) {
return slow;
}
}
return null;
}
public void delete(Node head)
{
Node current_node=detect(head);
Node temp_node=current_node;;
while(temp_node.next!=current_node)
{
temp_node=temp_node.next;
}
temp_node.next=null;
}
public void print_after_delete(){
delete(head);
Node current_node=head;
while(current_node!=null)
{
System.out.print(current_node.data+"->");
current_node=current_node.next;
}
System.out.print("null");
}
public static void main(String args[])
{
detect_remove_cycle_in_linkedlist ll=new detect_remove_cycle_in_linkedlist();
ll.head = new detect_remove_cycle_in_linkedlist.Node(1);
ll.head.next = new detect_remove_cycle_in_linkedlist.Node(2);
ll.head.next.next = new detect_remove_cycle_in_linkedlist.Node(3);
ll.head.next.next.next = new detect_remove_cycle_in_linkedlist.Node(4);
ll.head.next.next.next.next = new detect_remove_cycle_in_linkedlist.Node(5);
ll.head.next.next.next.next.next = new detect_remove_cycle_in_linkedlist.Node(6);
ll.head.next.next.next.next.next.next = ll.head.next.next;
Node jj=ll.detect(ll.head);
System.out.println(jj.data);
ll.print_after_delete();
}
}