-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathCircularLinkedLIst.java
126 lines (112 loc) · 2.83 KB
/
CircularLinkedLIst.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
120
121
122
123
124
125
126
package Lists;
public class CircularLinkedLIst<T> {
private int size = 0;
private Node head, tail;
private class Node<T> {
T val;
Node next;
public Node(T val, Node next) {
this.val = val;
this.next = next;
}
}
public void add(T val) {
if (head == null) {
head = new Node(val, null);
tail = head;
tail.next = head;
size++;
return;
}
tail.next = new Node(val, head);
tail = tail.next;
size++;
}
public void add(int index, T val) {
if (index > size) {
int t = index - size;
while (t > 0) {
add(null);
t--;
}
add(val);
return;
}
if (index == size) {
add(val);
return;
}
Node temp = head;
while (index > 1) {
temp = temp.next;
index--;
}
Node node = new Node(val, temp.next);
temp.next = node;
}
public int size() {
return size;
}
public boolean isEmpty() {
return size() == 0;
}
public T remove(int index) throws Exception {
if (index > size - 1) {
throw new Exception("No such index exception");
}
if (index == 0) {
T retval = (T) head.val;
head = head.next;
tail.next = head;
size--;
return retval;
}
if (index == size - 1) {
int tsize = size - 1;
Node temp = head;
while (tsize > 1) {
temp = temp.next;
tsize--;
}
T retval = (T) temp.next.val;
temp.next = head;
size--;
return retval;
}
Node temp = head;
while (index > 0) {
temp = temp.next;
index--;
}
T retval = (T) temp.val;
temp.val = temp.next.val;
temp.next = temp.next.next;
size--;
return retval;
}
public T get(int index) throws Exception {
Node temp = head;
if (index > size - 1) {
throw new Exception("No Such Index Exception");
}
while (index > 0) {
temp = temp.next;
index--;
}
return (T) temp.val;
}
@Override
public String toString() {
StringBuilder ret = new StringBuilder("[");
Node temp = head;
if (temp == null) {
return ret.append("]").toString();
}
do {
ret.append(temp.val + ",");
temp = temp.next;
} while (temp != head);
String t = ret.substring(0, ret.length() - 1);
return new StringBuilder(t).append("]").toString();
}
}