-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDeletion of Doubly Link List at Beginning
104 lines (87 loc) · 2.77 KB
/
Deletion of Doubly Link List at Beginning
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
package DataS;
public class Deletion_Doubly_Link_Beginning {
// Inner class representing a node in the doubly linked list
private static class Node {
int data;
Node prev;
Node next;
Node(int data) {
this.data = data;
this.prev = null;
this.next = null;
}
}
private Node head; // Head of the doubly linked list
public Deletion_Doubly_Link_Beginning() {
this.head = null;
}
// Method to insert a node at the beginning of the list
public void insertAtBeginning(int data) {
Node newNode = new Node(data);
if (head == null) {
head = newNode;
} else {
newNode.next = head;
head.prev = newNode;
head = newNode;
}
}
// Method to delete a node at the beginning of the list
public void deleteAtBeginning() {
if (head == null) {
System.out.println("List is empty. Nothing to delete.");
return;
}
if (head.next == null) {
// Only one node in the list
head = null;
} else {
// More than one node in the list
head = head.next;
head.prev = null;
}
System.out.println("Node deleted at the beginning.");
}
// Method to print the list forward
public void printListForward() {
System.out.print("List (forward): ");
Node current = head;
while (current != null) {
System.out.print(current.data + " ");
current = current.next;
}
System.out.println();
}
// Method to print the list backward
public void printListBackward() {
System.out.print("List (backward): ");
Node current = head;
// Move to the last node
while (current != null && current.next != null) {
current = current.next;
}
// Traverse backward using the prev pointers
while (current != null) {
System.out.print(current.data + " ");
current = current.prev;
}
System.out.println();
}
public static void main(String[] args) {
Deletion_Doubly_Link_Beginning dll = new Deletion_Doubly_Link_Beginning();
// Insert nodes at the beginning
dll.insertAtBeginning(11);
dll.insertAtBeginning(27);
dll.insertAtBeginning(31);
// Print the list forward
dll.printListForward();
// Print the list backward
dll.printListBackward();
// Delete a node at the beginning
dll.deleteAtBeginning();
// Print the list forward after deletion
dll.printListForward();
// Print the list backward after deletion
dll.printListBackward();
}
}