-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdoubleLL.java
More file actions
81 lines (72 loc) · 1.82 KB
/
Copy pathdoubleLL.java
File metadata and controls
81 lines (72 loc) · 1.82 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
public class doubleLL {
class Node {
int data;
Node prev;
Node next;
Node(int data) {
this.data = data;
}
}
private Node head;
// Method to add a node at the end of the list
public void add(int data) {
Node newNode = new Node(data);
if (head == null) {
head = newNode;
return;
}
Node temp = head;
while (temp.next != null) {
temp = temp.next;
}
temp.next = newNode;
newNode.prev = temp;
}
// Method to delete a node with a given value
public void delete(int data) {
if (head == null) {
return;
}
Node temp = head;
while (temp != null && temp.data != data) {
temp = temp.next;
}
if (temp == null) {
return; // Element not found
}
if (temp.prev != null) {
temp.prev.next = temp.next;
} else {
head = temp.next; // Deleting the head node
}
if (temp.next != null) {
temp.next.prev = temp.prev;
}
}
// Method to display the contents of the list
public void display() {
Node temp = head;
while (temp != null) {
System.out.print(temp.data + " ");
temp = temp.next;
}
System.out.println();
}
public static void main(String[] args) {
doubleLL dll = new doubleLL();
dll.add(1);
dll.add(2);
dll.add(3);
dll.add(4);
dll.add(5);
System.out.println("Original List:");
dll.display();
dll.delete(3);
System.out.println("List after deleting element 3:");
dll.display();
}
}
// Original List:
// 1 2 3 4 5
// List after deleting element 3:
// 1 2 4 5