Which of the following is a key advantage of using a doubly linked list over a singly linked list?
Think about how nodes are connected in both lists.
Doubly linked lists have two pointers per node, allowing traversal forwards and backwards, unlike singly linked lists which only allow forward traversal.
What will be the output of the following C++ code that traverses a doubly linked list backwards?
struct Node {
int data;
Node* next;
Node* prev;
};
// Assume list: 1 <-> 2 <-> 3 <-> 4
Node* tail = new Node{4, nullptr, nullptr};
Node* n3 = new Node{3, tail, nullptr};
tail->prev = n3;
Node* n2 = new Node{2, n3, nullptr};
n3->prev = n2;
Node* head = new Node{1, n2, nullptr};
n2->prev = head;
Node* current = tail;
while (current != nullptr) {
std::cout << current->data << " ";
current = current->prev;
}Start from the tail and move using the prev pointer.
The code starts at the tail node and moves backwards using the prev pointer, printing nodes in reverse order: 4 3 2 1.
What is the bug in the following C++ code snippet that deletes a node from a doubly linked list?
void deleteNode(Node* del) { if (del == nullptr) return; if (del->prev != nullptr) { del->prev->next = del->next; } if (del->next != nullptr) { del->next->prev = del->prev; } delete del; }
Consider what happens if the node to delete is the first node.
If the node to delete is the head, the head pointer must be updated to the next node. This code does not handle that, so the head pointer becomes invalid.
Given the doubly linked list 10 <-> 20 <-> 30, what is the list after inserting 40 at the tail?
struct Node {
int data;
Node* next;
Node* prev;
};
Node* head = new Node{10, nullptr, nullptr};
Node* n2 = new Node{20, nullptr, head};
head->next = n2;
Node* n3 = new Node{30, nullptr, n2};
n2->next = n3;
// Insert 40 at tail
Node* tail = n3;
Node* newNode = new Node{40, nullptr, tail};
tail->next = newNode;
// Print list forward
Node* current = head;
while (current != nullptr) {
std::cout << current->data << " ";
current = current->next;
}Check how the new node is linked to the tail.
The new node 40 is linked after 30, making the list: 10 20 30 40.
Compared to a singly linked list, what is the main memory overhead of using a doubly linked list?
Think about what extra information each node holds in a doubly linked list.
Doubly linked list nodes have two pointers: one to the next node and one to the previous node, which increases memory usage compared to singly linked list nodes that have only one pointer.
