Doubly Linked List
Doubly Linked List
● It consists of an information field and two pointer fields. The information field contains
the data. The first pointer field contains an address of the previous node, whereas another
pointer field contains a reference to the next node. Thus, we can go in both directions
(backward as well as forward).
● In a singly linked list, you can only move in one direction because each node only has the
address of the next node and doesn't keep track of the previous ones. However, a doubly
linked list solves this problem. Each node in a doubly linked list has the address of both the
next and the previous node. This means you can move forward and backward through the
list, making it easier to find and use information about previous nodes.
#include <stdio.h>
#include <stdlib.h>
// Insert at beginning
void insertAtBeginning(int data) {
Node* newNode = createNode(data);
if (head == NULL) {
head = newNode;
tail = newNode;
} else {
newNode->next = head;
head->prev = newNode;
head = newNode;
}
}
// Insert at end
void insertAtEnd(int data) {
Node* newNode = createNode(data);
if (tail == NULL) {
head = newNode;
tail = newNode;
} else {
newNode->prev = tail;
tail->next = newNode;
tail = newNode;
}
}
// Print forward
void printForward() {
Node* temp = head;
while (temp != NULL) {
printf("%d ", temp->data);
temp = temp->next;
}
printf("\n");
}
// Print backward
void printBackward() {
Node* temp = tail;
while (temp != NULL) {
printf("%d ", temp->data);
temp = temp->prev;
}
printf("\n");
}
int main() {
insertAtEnd(1);
insertAtEnd(2);
insertAtEnd(3);
insertAtBeginning(0);
insertAtBeginning(-1);
printf("Forward: ");
printForward();
printf("Backward: ");
printBackward();
deleteFromBeginning();
deleteFromEnd();
return 0;
}