Skip to content

Doubly Linked List

Course: Linked List - chapter 6

In a normal linked list, each node stores the data and a pointer to the next node. In DLLs, each node stores an additional value which is a pointer to the previous node as well. So, in a DLL you can easily travel in both directions i.e right to left and left to right.

Most of the things are similar to single linked list, except we can now travel in both directions. Also, in all the operations, we have to handle the previous node pointer as well. Let’s look into some operations.

class Node {
int data;
Node *next;
Node *prev;
public:
// constructors here
};
Node* addNodeAtEnd(Node *head, int x) {
if (head == NULL) {
head = new Node();
} else{
Node *curr = head;
while(curr->next != NULL) {
curr = curr->next;
}
// curr is added as a previous node to the new node
curr->next = new Node(x, NULL, curr);
}
return head;
}
Node *removeNode(Node *head, int K) {
if (head == NULL) return NULL;
else if (head->data == K) {
Node *curr = head;
head = head->next;
head->prev = NULL;
delete curr;
return head;
}
Node *curr = head;
while(curr != NULL and curr->data != K) {
curr = curr->next;
}
if (curr != NULL) {
curr->prev->next = curr->next;
curr->next->prev = curr->prev;
delete curr;
}
return head;
}