forked from LogicFirstTamil/DSA-in-JAVA
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCircularLinkedList.java
86 lines (70 loc) · 1.42 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
public class CircularLinkedList<T>{
Node last;
class Node{
T data;
Node next;
Node(T val){
data = val;
next = null;
}
}
CircularLinkedList(){
last = null;
}
public void insertAtBeginning(T val){
Node newNode = new Node(val);
if(last==null) {
newNode.next = newNode;
last = newNode;
}
else {
newNode.next = last.next;
last.next = newNode;
}
}
public void insertAtEnd(T val){
Node newNode = new Node(val);
if(last==null) {
newNode.next = newNode;
last = newNode;
}
else {
newNode.next = last.next;
last.next = newNode;
last=newNode;
}
}
public void display() {
if(last==null)
return;
Node temp = last.next;
do{
System.out.print(temp.data + " ");
temp = temp.next;
}while(temp!=last.next);
}
public T deleteAtBeginning() {
if(last==null)
throw new IndexOutOfBoundsException("Deletion attempted on empty list ");
T temp = last.next.data;
if(last.next==last)
last = null;
else
last.next = last.next.next;
return temp;
}
public void deleteAtEnd() {
if(last==null)
throw new IndexOutOfBoundsException("Deletion attempted on empty list ");
if(last.next==last)
last = null;
else {
Node temp = last.next;
while(temp.next!=last) {
temp = temp.next;
}
temp.next = last.next;
last = temp;
}
}
}