Complete the code to declare a pointer to the previous node in a doubly linked list node.
struct Node {
int data;
Node* next;
Node* [1];
};The pointer to the previous node in a doubly linked list is commonly named prev.
Complete the code to move backward in a doubly linked list using the previous pointer.
Node* current = tail; while (current != nullptr) { std::cout << current->data << " "; current = current->[1]; }
To move backward in a doubly linked list, use the prev pointer.
Fix the error in the code to insert a new node after a given node in a doubly linked list.
void insertAfter(Node* prev_node, int new_data) {
if (prev_node == nullptr) return;
Node* new_node = new Node();
new_node->data = new_data;
new_node->next = prev_node->next;
prev_node->next = [1];
new_node->prev = prev_node;
if (new_node->next != nullptr)
new_node->next->prev = new_node;
}prev_node->next to itself or to nullptr.We must set prev_node->next to point to the newly created node new_node.
Fill both blanks to correctly remove a node from a doubly linked list.
void deleteNode(Node** head_ref, Node* del) {
if (*head_ref == nullptr || del == nullptr) return;
if (*head_ref == del) *head_ref = del->[1];
if (del->next != nullptr) del->next->[2] = del->prev;
if (del->prev != nullptr) del->prev->next = del->next;
delete del;
}When deleting a node, update the head if needed by moving it to del->next. Then update the next node's prev pointer to skip the deleted node.
Fill all three blanks to traverse a doubly linked list forward and backward.
void printList(Node* node) {
Node* last = nullptr;
std::cout << "Forward: ";
while (node != nullptr) {
std::cout << node->[1] << " ";
last = node;
node = node->[2];
}
std::cout << "\nBackward: ";
while (last != nullptr) {
std::cout << last->[3] << " ";
last = last->prev;
}
}To print the list, access the data field for values. Move forward using next pointer, and backward using prev pointer.
