doubly-linked-list-using-C-Data-Structure
admin
#doubly-linked-list-using-C-Data-Structure
A doubly linked list is a versatile data structure that enhances the capabilities of a traditional singly linked list. In this structure, each node contains three parts: the data element, a pointer to the previous node, and a pointer to the next node in the sequence. This bidirectional linkage allows traversal in both directions, making it highly efficient for applications like undo functionality, navigation systems, and data manipulation.
Below is an example of a doubly linked list implementation in C. It covers key operations like appending nodes, traversing in forward and backward directions, searching for nodes, updating values, and inserting/deleting nodes based on specific criteria.
#include <stdio.h>
#include <stdlib.h>
struct node {
int no;
struct node *next, *pre;
};
struct node *start = NULL, *last = NULL;
// Append a node
void append() {
struct node *n;
n = (struct node *)malloc(sizeof(struct node));
printf("\n Enter No :");
scanf("%d", &n->no);
n->next = NULL;
if (start == NULL) {
start = last = n;
start->pre = NULL;
printf("\n Node Appended ");
return;
}
last->next = n;
n->pre = last;
last = n;
printf("\n Node Appended ");
}
// Forward traversal
void ftraverse() {
struct node *p = start;
if (start == NULL) {
printf("\n Empty Linked List ");
return;
}
printf("\n START ");
while (p != NULL) {
printf(" %d", p->no);
p = p->next;
}
printf(" END\n");
}
// Backward traversal
void btraverse() {
struct node *p = last;
if (last == NULL) {
printf("\n Empty Linked List ");
return;
}
printf("\n LAST ");
while (p != NULL) {
printf(" %d", p->no);
p = p->pre;
}
printf(" START\n");
}
// Main function
int main() {
int ch;
do {
printf("\n1 Append\n2 Forward Traversal\n3 Backward Traversal\n0 Exit\nEnter Choice: ");
scanf("%d", &ch);
switch (ch) {
case 1: append(); break;
case 2: ftraverse(); break;
case 3: btraverse(); break;
case 0: break;
default: printf("\n Invalid Choice\n");
}
} while (ch != 0);
return 0;
}
The doubly linked list is an indispensable data structure that provides a balance between complexity and functionality. Its ability to traverse in both directions and perform efficient insertions and deletions makes it suitable for a wide range of applications. Learning and mastering this structure is essential for anyone looking to excel in data structure algorithms.
Pro Tip: Practice implementing a doubly linked list in different programming languages to understand its versatility and underlying logic better.