class Node { int data; Node prev, next; Node(int d) { data = d; prev = next = null; } } class DoublyLinkedList { Node head; void push(int new_data) { Node new_node = new Node(new_data); new_node.next = head; if (head != null) head.prev = new_node; head = new_node; } void deleteFromBeginning() { if (head == null) return; head = head.next; if (head != null) head.prev = null; } void printList() { Node temp = head; while (temp != null) { System.out.print(temp.data + " <-> "); temp = temp.next; } System.out.println("null"); } } public class Main { public static void main(String[] args) { DoublyLinkedList dll = new DoublyLinkedList(); dll.push(3); dll.push(2); dll.push(1); dll.deleteFromBeginning(); dll.printList(); } }
The list initially is 1 <-> 2 <-> 3 <-> null after pushing 1, 2, 3 in that order.
Deleting from beginning removes the first node (1), so the new head is 2.
Thus, the list becomes 2 <-> 3 <-> null.
The delete method first checks if the head is null (empty list).
If yes, it returns immediately without changes or errors.
void deleteFromBeginning() {
if (head == null) return;
head = head.next;
head.prev = null;
}If the list has only one node, head.next is null.
After setting head = head.next, head becomes null.
Then head.prev causes NullPointerException because head is null.
class Node { int data; Node prev, next; Node(int d) { data = d; prev = next = null; } } class DoublyLinkedList { Node head; void push(int new_data) { Node new_node = new Node(new_data); new_node.next = head; if (head != null) head.prev = new_node; head = new_node; } void deleteFromBeginning() { if (head == null) return; head = head.next; if (head != null) head.prev = null; } void printList() { Node temp = head; while (temp != null) { System.out.print(temp.data + " <-> "); temp = temp.next; } System.out.println("null"); } } public class Main { public static void main(String[] args) { DoublyLinkedList dll = new DoublyLinkedList(); dll.push(4); dll.push(3); dll.push(2); dll.push(1); dll.deleteFromBeginning(); dll.deleteFromBeginning(); dll.printList(); } }
Initial list after pushes: 1 <-> 2 <-> 3 <-> 4 <-> null
First deletion removes 1, list becomes 2 <-> 3 <-> 4 <-> null
Second deletion removes 2, list becomes 3 <-> 4 <-> null
In a doubly linked list, each node's prev points to the previous node.
If after deletion the new head's prev is not set to null, it still points to the removed node.
This causes backward traversal to access invalid memory or wrong nodes.
