-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCircular Linked List Insertion & Deletion
More file actions
132 lines (110 loc) · 3.04 KB
/
Circular Linked List Insertion & Deletion
File metadata and controls
132 lines (110 loc) · 3.04 KB
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
127
128
129
130
131
132
class Node {
int data;
Node next;
public Node(int data) {
this.data = data;
this.next = null;
}
}
class CircularLinkedList {
private Node head = null;
private Node tail = null;
// Insert at the beginning
public void insertAtBeginning(int data) {
Node newNode = new Node(data);
if (head == null) {
head = newNode;
tail = newNode;
newNode.next = head;
} else {
newNode.next = head;
head = newNode;
tail.next = head;
}
}
// Insert at the end
public void insertAtEnd(int data) {
Node newNode = new Node(data);
if (head == null) {
head = newNode;
tail = newNode;
newNode.next = head;
} else {
tail.next = newNode;
tail = newNode;
tail.next = head;
}
}
// Insert after a given node
public void insertAfter(Node prevNode, int data) {
if (prevNode == null) {
System.out.println("The given previous node cannot be null");
return;
}
Node newNode = new Node(data);
newNode.next = prevNode.next;
prevNode.next = newNode;
if (prevNode == tail) {
tail = newNode;
}
}
// Delete a node
public void deleteNode(int key) {
if (head == null) {
return;
}
Node current = head;
Node prev = null;
// If the head node itself holds the key
if (current.data == key) {
if (head == tail) {
head = null;
tail = null;
} else {
head = head.next;
tail.next = head;
}
return;
}
// Search for the key
do {
prev = current;
current = current.next;
} while (current != head && current.data != key);
// If the key was found
if (current.data == key) {
prev.next = current.next;
if (current == tail) {
tail = prev;
}
}
}
// Display the list
public void display() {
if (head == null) {
System.out.println("List is empty");
return;
}
Node current = head;
do {
System.out.print(current.data + " ");
current = current.next;
} while (current != head);
System.out.println();
}
public static void main(String[] args) {
CircularLinkedList list = new CircularLinkedList();
list.insertAtEnd(1);
list.insertAtEnd(2);
list.insertAtEnd(3);
list.insertAtBeginning(0);
System.out.print("Circular Linked List: ");
list.display();
list.insertAfter(list.head.next, 1);
System.out.print("After inserting 1 after the second node: ");
list.display();
list.deleteNode(2);
System.out.print("After deleting node with data 2: ");
list.display();
}
}