-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDoublyLinkedList
110 lines (94 loc) · 2.71 KB
/
DoublyLinkedList
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
package javaprograms;
class DoublyLinkedList {
// Node class for doubly linked list
private class Node {
int data;
Node prev;
Node next;
Node(int data) {
this.data = data;
this.prev = null;
this.next = null;
}
}
private Node head;
// Insert a new node at the end of the list
public void insert(int data) {
Node newNode = new Node(data);
if (head == null) {
head = newNode;
} else {
Node temp = head;
while (temp.next != null) {
temp = temp.next;
}
temp.next = newNode;
newNode.prev = temp;
}
}
// Delete a node with a given value
public void delete(int data) {
if (head == null) {
System.out.println("List is empty.");
return;
}
Node temp = head;
// Traverse to find the node to delete
while (temp != null && temp.data != data) {
temp = temp.next;
}
// Node with the given data is not found
if (temp == null) {
System.out.println("Element " + data + " not found in the list.");
return;
}
// If the node to be deleted is the head node
if (temp == head) {
head = head.next;
if (head != null) {
head.prev = null;
}
} else {
// Update the links of the previous and next nodes
if (temp.next != null) {
temp.next.prev = temp.prev;
}
if (temp.prev != null) {
temp.prev.next = temp.next;
}
}
System.out.println("Element " + data + " deleted from the list.");
}
// Display the contents of the list
public void display() {
if (head == null) {
System.out.println("List is empty.");
return;
}
Node temp = head;
System.out.print("List contents: ");
while (temp != null) {
System.out.print(temp.data + " ");
temp = temp.next;
}
System.out.println();
}
}
public class Main {
public static void main(String[] args) {
DoublyLinkedList list = new DoublyLinkedList();
// Insert elements into the list
list.insert(10);
list.insert(20);
list.insert(30);
list.insert(40);
// Display list contents
System.out.println("Original list:");
list.display();
// Delete an element
list.delete(20);
// Display list contents after deletion
System.out.println("List after deletion:");
list.display();
}
}