-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCircular_Doubly_Linked_List(Insertion )
More file actions
111 lines (99 loc) · 2.9 KB
/
Circular_Doubly_Linked_List(Insertion )
File metadata and controls
111 lines (99 loc) · 2.9 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
package DataS;
class CircularDoublyLinkedList {
Node head;
CircularDoublyLinkedList() {
head = null;
}
class Node {
int data;
Node next;
Node prev;
Node(int data) {
this.data = data;
this.next = null;
this.prev = null;
}
}
// Insertion at the beginning
void insertAtBeginning(int data) {
Node newNode = new Node(data);
if (head == null) {
head = newNode;
newNode.next = newNode;
newNode.prev = newNode;
} else {
Node last = head.prev;
newNode.next = head;
newNode.prev = last;
last.next = newNode;
head.prev = newNode;
head = newNode;
}
}
// Insertion at the end
void insertAtEnd(int data) {
Node newNode = new Node(data);
if (head == null) {
head = newNode;
newNode.next = newNode;
newNode.prev = newNode;
} else {
Node last = head.prev;
newNode.next = head;
newNode.prev = last;
last.next = newNode;
head.prev = newNode;
}
}
// Insertion at a specific location
void insertAtPosition(int data, int position) {
Node newNode = new Node(data);
if (position == 1) {
insertAtBeginning(data);
return;
}
Node temp = head;
for (int i = 1; i < position - 1 && temp.next != head; i++) {
temp = temp.next;
}
Node nextNode = temp.next;
newNode.next = nextNode;
newNode.prev = temp;
temp.next = newNode;
nextNode.prev = newNode;
}
// Display the list
void display() {
if (head == null) {
System.out.println("List is empty");
return;
}
Node temp = head;
do {
System.out.print(temp.data + " ");
temp = temp.next;
} while (temp != head);
System.out.println();
}
public static void main(String[] args) {
CircularDoublyLinkedList cdll = new CircularDoublyLinkedList();
// Insertion at the beginning
System.out.println("Insertion at the beginning:");
cdll.insertAtBeginning(1);
cdll.display(); // Output: 1
cdll.insertAtBeginning(2);
cdll.display(); // Output: 2 1
cdll.insertAtBeginning(3);
cdll.display(); // Output: 3 2 1
// Insertion at the end
System.out.println("Insertion at the end:");
cdll.insertAtEnd(4);
cdll.display(); // Output: 3 2 1 4
cdll.insertAtEnd(5);
cdll.display(); // Output: 3 2 1 4 5
// Insertion at a specific position
System.out.println("Insertion at a specific position:");
cdll.insertAtPosition(6, 3);
cdll.display(); // Output: 3 2 6 1 4 5
}
}