-
Notifications
You must be signed in to change notification settings - Fork 0
/
CircularLL.java
119 lines (98 loc) · 2.71 KB
/
CircularLL.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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
public class CircularLL {
public static class Node {
int data;
Node next;
public Node(int data) {
this.data = data;
}
}
public static Node last;
public static Node AddToEmpty(Node last, int data) {
if (last != null) {
return last;
}
Node newnode = new Node(data);
last = newnode;
newnode.next = last;
return last;
}
public static Node AddFront(Node last, int data) {
if (last == null) {
return AddToEmpty(last, data);
}
Node newnode = new Node(data);
newnode.next = last.next;
last.next = newnode;
return last;
}
public static Node AddEnd(Node last, int data) {
if (last == null) {
return AddToEmpty(last, data);
}
Node newnode = new Node(data);
newnode.next = last.next;
last.next = newnode;
last = newnode;
return last;
}
public static void PrintCLL(Node last) {
if (last == null) {
System.out.println("CLL IS EMPTY");
return;
}
Node temp = last.next;
while (temp != last) {
System.out.print(temp.data);
System.out.print("->");
temp = temp.next;
}
System.out.print(last.data);
}
public static int Remove(Node last, int key) {
if (last == null) {
return -1;
}
if (last.next.data == key) {
int data = last.next.data;
last.next = last.next.next;
return data;
}
if (last.data == key) {
Node prev = last;
while (prev.next != last) {
prev = prev.next;
}
int data = last.data;
prev.next = last.next; //<----------------- CAN NOT GET WHY IT'S STUCK IN THE INFINITE LOOP???
// last = prev;
return data;
}
Node vary = last.next;
int key_pos = 1;
while (vary.data != key) {
key_pos++;
vary = vary.next;
}
int data = vary.data;
Node prev = last.next;
int j = 0;
while (j < key_pos - 2) {
prev = prev.next;
j++;
}
prev.next = prev.next.next;
return data;
}
public static void main(String[] args) {
// Node last = null;
last = AddEnd(last, 1);
last = AddEnd(last, 2);
last = AddEnd(last, 3);
last = AddEnd(last, 4);
last = AddEnd(last, 5);
PrintCLL(last);
System.out.println();
System.out.println(Remove(last, 5));
PrintCLL(last);
}
}