top of page

Doubly Linked List



A doubly linked list is a data structure in which each node contains not only a data element but also two pointers, one pointing to the previous node and one pointing to the next node in the list. This allows for efficient traversal in both directions, as well as easy insertion and deletion of nodes at any position in the list.


#include <stdio.h>

#include <stdlib.h>


struct Node {

int data;

struct Node* prev;

struct Node* next;

};


struct DoublyLinkedList {

struct Node* head;

struct Node* tail;

int count;

};


struct Node* create_node(int data) {

struct Node* node = (struct Node*)malloc(sizeof(struct Node));

node->data = data;

node->prev = NULL;

node->next = NULL;

return node;

}


struct DoublyLinkedList* create_list() {

struct DoublyLinkedList* list = (struct DoublyLinkedList*)malloc(sizeof(struct DoublyLinkedList));

list->head = NULL;

list->tail = NULL;

list->count = 0;

return list;

}


void append(struct DoublyLinkedList* list, int data) {

struct Node* node = create_node(data);


if (list->head == NULL) {

list->head = node;

list->tail = node;

} else {

node->prev = list->tail;

list->tail->next = node;

list->tail = node;

}


list->count++;

}


int remove_node(struct DoublyLinkedList* list, int data) {

struct Node* current = list->head;


while (current != NULL) {

if (current->data == data) {

if (current == list->head && current == list->tail) {

list->head = NULL;

list->tail = NULL;

} else if (current == list->head) {

list->head = current->next;

list->head->prev = NULL;

} else if (current == list->tail) {

list->tail = current->prev;

list->tail->next = NULL;

} else {

current->prev->next = current->next;

current->next->prev = current->prev;

}


free(current);

list->count--;

return 1;

}


current = current->next;

}


return 0;

}


void print_list(struct DoublyLinkedList* list) {

struct Node* current = list->head;


while (current != NULL) {

printf("%d ", current->data);

current = current->next;

}


printf("\n");

}


int main() {

struct DoublyLinkedList* list = create_list();


append(list, 1);

append(list, 2);

append(list, 3);


print_list(list); // output: 1 2 3


remove_node(list, 2);


print_list(list); // output: 1 3


return 0;

}



0 views0 comments

Recent Posts

See All

Stack Using Queue

A stack can be implemented using two queues in C. The basic idea is to use one queue for enqueue operations and another for dequeue operations. When an element is pushed onto the stack, it is enqueued

bottom of page