A doubly linked list has pointers to both the next and previous nodes, allowing traversal in both directions. A singly linked list only has a pointer to the next node, so it can only be traversed forward.
class Node { int data; Node next, prev; Node(int d) { data = d; next = prev = null; } } public class DLLTest { public static void main(String[] args) { Node head = new Node(1); Node second = new Node(2); Node third = new Node(3); head.next = second; second.prev = head; second.next = third; third.prev = second; Node tail = third; while (tail != null) { System.out.print(tail.data + " "); tail = tail.prev; } } }
The code starts from the last node (tail) and moves backward using the prev pointer, printing 3, then 2, then 1.
class Node { int data; Node next, prev; Node(int d) { data = d; next = prev = null; } } public class DLLInsert { public static void main(String[] args) { Node head = new Node(1); Node second = new Node(3); head.next = second; Node newNode = new Node(2); newNode.next = head.next; head.next = newNode; newNode.prev = head; System.out.print(head.next.next.prev.data); } }
The code forgets to update head.next.next.prev to point back to newNode. So head.next.next.prev is null, causing a NullPointerException when accessing data.
Option C is missing a semicolon between next = null and prev = null, causing a syntax error.
A doubly linked list is ideal because it allows moving forward and backward through the playlist efficiently. Arrays allow random access but moving backward requires extra logic. Singly linked lists only allow forward movement. Stacks do not support moving backward.
