top of page

Doubly Circular Linked List

A doubly circular linked list is a type of linked list where each node has both a "next" and a "previous" pointer, allowing for traversal in both directions. Additionally, the last node in the list points back to the first node, forming a circle.

#include <stdio.h>

#include <stdlib.h>


struct Node {

int data;

struct Node* next;

struct Node* prev;

};


struct DoublyCircularLinkedList {

struct Node* head;

int count;

};


struct Node* create_node(int data) {

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

node->data = data;

node->next = NULL;

node->prev = NULL;

return node;

}


struct DoublyCircularLinkedList* create_list() {

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

list->head = NULL;

list->count = 0;

return list;

}


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

struct Node* node = create_node(data);


if (list->head == NULL) {

list->head = node;

node->next = node; // make the node point to itself

node->prev = node;

} else {

node->next = list->head;

node->prev = list->head->prev;

list->head->prev->next = node;

list->head->prev = node;

}


list->count++;

}


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

if (list->head == NULL) {

return 0;

}


struct Node* current = list->head;


do {

if (current->data == data) {

if (current == list->head) {

list->head = current->next;

}


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

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

free(current);

list->count--;

return 1;

}


current = current->next;

} while (current != list->head);


return 0;

}


void print_list(struct DoublyCircularLinkedList* list) {

if (list->head == NULL) {

return;

}


struct Node* current = list->head;


do {

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

current = current->next;

} while (current != list->head);


printf("\n");

}


int main() {

struct DoublyCircularLinkedList* 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;

}


2 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