Files
ds-lab-codes/DoublyLL.c
T
2025-12-08 23:41:37 +05:30

137 lines
3.0 KiB
C

#include <stdio.h>
#include <stdlib.h>
typedef struct element {
int key;
} element;
typedef struct node *nodeptr;
typedef struct node {
nodeptr llink;
element item;
nodeptr rlink;
} node;
void insert(nodeptr head, int data);
void delete(nodeptr head, nodeptr deleted);
void display(nodeptr head);
nodeptr search(nodeptr head, int key);
int main() {
int choice, data;
nodeptr node_to_delete;
nodeptr head = (nodeptr)malloc(sizeof(node));
if (head == NULL) {
fprintf(stderr, "Memory allocation failed for head node.\n");
exit(1);
}
head->llink = head;
head->rlink = head;
while (1) {
printf("\n--- Doubly Linked List Menu ---\n");
printf("1. Insert (at front)\n");
printf("2. Delete (by key)\n");
printf("3. Display List\n");
printf("4. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);
switch (choice) {
case 1:
printf("Enter number to insert: ");
scanf("%d", &data);
insert(head, data);
printf("Item %d inserted.\n", data);
break;
case 2:
printf("Enter number to delete: ");
scanf("%d", &data);
node_to_delete = search(head, data);
if (node_to_delete == NULL) {
printf("Item %d not found in the list.\n", data);
} else {
delete(head, node_to_delete);
printf("Item %d deleted.\n", data);
}
break;
case 3:
display(head);
break;
case 4:
printf("Exiting program.\n");
free(head);
exit(0);
default:
printf("Invalid choice. Please try again.\n");
}
}
return 0;
}
void insert(nodeptr head, int data) {
nodeptr newnode = (nodeptr)malloc(sizeof(node));
if (newnode == NULL) {
fprintf(stderr, "Memory allocation failed for new node!\n");
exit(1);
}
newnode->item.key = data;
newnode->llink = head;
newnode->rlink = head->rlink;
head->rlink->llink = newnode;
head->rlink = newnode;
}
void delete(nodeptr head, nodeptr deleted) {
if (head == deleted) {
printf("Deletion of the head node not permitted!\n");
} else {
deleted->llink->rlink = deleted->rlink;
deleted->rlink->llink = deleted->llink;
free(deleted);
}
}
nodeptr search(nodeptr head, int key) {
nodeptr temp = head->rlink;
while (temp != head) {
if (temp->item.key == key) {
return temp;
}
temp = temp->rlink;
}
return NULL;
}
void display(nodeptr head) {
nodeptr temp = head->rlink;
if (temp == head) {
printf("List is empty.\n");
return;
}
printf("List: ");
while (temp != head) {
printf("%d ", temp->item.key);
temp = temp->rlink;
}
printf("\n");
}