Doubly Linked Lists
Doubly Linked Lists
To develop a doubly linked list in Java with forward and backward traversal, along with
insertion and deletion.
class DoublyLinkedList {
// Node class for doubly linked list
static class Node {
int data;
Node next;
Node prev;
if (head == null) {
head = newNode; // If the list is empty, make the new node as head
return;
}
if (head == null) {
head = newNode; // If the list is empty, make the new node as head
return;
}
while (current != null && current.data != data) { // Find the node to be deleted
current = current.next;
}
if (current == null) {
System.out.println("Node not found.");
return;
}
if (current == null) {
System.out.println("List is empty.");
return;
}
// Forward traversal
System.out.println("Forward Traversal:");
dll.traverseForward(); // Output: 5 10 20 30 40
// Backward traversal
System.out.println("Backward Traversal:");
dll.traverseBackward(); // Output: 40 30 20 10 5
// Delete a node
dll.deleteNode(20);
System.out.println("After Deleting 20:");