Tracing Doubly Linked List Operations
Consider the following DoublyLinkedList class. What is printed as a result of executing the main method?
public class DoublyLinkedList {
class Node {
int val;
Node prev, next;
Node(int v) { val = v; }
}
Node head, tail;
public void addAtHead(int v) {
Node n = new Node(v);
if(head == null) {
head = tail = n;
} else {
n.next = head;
head.prev = n;
head = n;
}
}
public void addAtTail(int v) {
Node n = new Node(v);
if(tail == null) {
head = tail = n;
} else {
tail.next = n;
n.prev = tail;
tail = n;
}
}
public void remove(int v) {
Node current = head;
while(current != null) {
if(current.val == v) {
if(current.prev != null) {
current.prev.next = current.next;
} else {
head = current.next;
}
if(current.next != null) {
current.next.prev = current.prev;
} else {
tail = current.prev;
}
break;
}
current = current.next;
}
}
public void display() {
Node current = head;
while(current != null) {
System.out.print(current.val + " ");
current = current.next;
}
System.out.println();
}
public static void main(String[] args) {
DoublyLinkedList dll = new DoublyLinkedList();
dll.addAtHead(4);
dll.addAtTail(8);
dll.addAtHead(2);
dll.addAtTail(10);
dll.remove(8);
dll.display();
}
}
A
2 8 10
B
2 4 10
C
2 4 8
D
4 2 10
Question Leaderboard
Not enough data yet to show leaderboard.
APFIVE