mirror of
https://github.com/Manoj-HV30/ds-lab-codes.git
synced 2026-05-16 19:35:22 +00:00
132 lines
2.4 KiB
C
132 lines
2.4 KiB
C
#include <stdio.h>
|
|
#include <stdlib.h>
|
|
|
|
/* Node structure */
|
|
typedef struct node {
|
|
int data;
|
|
struct node *prev;
|
|
struct node *next;
|
|
} NODE;
|
|
|
|
/* Global head pointer */
|
|
NODE *head = NULL;
|
|
|
|
/* Insert node at end (Create list) */
|
|
void insert(int value) {
|
|
NODE *newNode, *temp;
|
|
|
|
newNode = (NODE *)malloc(sizeof(NODE));
|
|
if (!newNode) {
|
|
printf("Memory allocation failed\n");
|
|
return;
|
|
}
|
|
|
|
newNode->data = value;
|
|
newNode->next = NULL;
|
|
|
|
if (head == NULL) {
|
|
newNode->prev = NULL;
|
|
head = newNode;
|
|
printf("Inserted %d\n", value);
|
|
return;
|
|
}
|
|
|
|
temp = head;
|
|
while (temp->next != NULL) {
|
|
temp = temp->next;
|
|
}
|
|
|
|
temp->next = newNode;
|
|
newNode->prev = temp;
|
|
|
|
printf("Inserted %d\n", value);
|
|
}
|
|
|
|
/* Delete node by value */
|
|
void delete_value(int value) {
|
|
NODE *temp = head;
|
|
|
|
if (head == NULL) {
|
|
printf("List is empty\n");
|
|
return;
|
|
}
|
|
|
|
while (temp != NULL && temp->data != value) {
|
|
temp = temp->next;
|
|
}
|
|
|
|
if (temp == NULL) {
|
|
printf("Element not found\n");
|
|
return;
|
|
}
|
|
|
|
if (temp == head) {
|
|
head = temp->next;
|
|
if (head != NULL)
|
|
head->prev = NULL;
|
|
} else {
|
|
temp->prev->next = temp->next;
|
|
if (temp->next != NULL)
|
|
temp->next->prev = temp->prev;
|
|
}
|
|
|
|
free(temp);
|
|
printf("Deleted %d\n", value);
|
|
}
|
|
|
|
/* Display list */
|
|
void display() {
|
|
NODE *temp = head;
|
|
|
|
if (head == NULL) {
|
|
printf("List is empty\n");
|
|
return;
|
|
}
|
|
|
|
printf("List: ");
|
|
while (temp != NULL) {
|
|
printf("%d <-> ", temp->data);
|
|
temp = temp->next;
|
|
}
|
|
printf("NULL\n");
|
|
}
|
|
|
|
/* Main function */
|
|
int main() {
|
|
int choice, value;
|
|
|
|
while (1) {
|
|
printf("\n--- DOUBLY LINKED LIST MENU ---\n");
|
|
printf("1. Insert\n");
|
|
printf("2. Delete\n");
|
|
printf("3. Display\n");
|
|
printf("4. Exit\n");
|
|
printf("Enter choice: ");
|
|
scanf("%d", &choice);
|
|
|
|
switch (choice) {
|
|
case 1:
|
|
printf("Enter value: ");
|
|
scanf("%d", &value);
|
|
insert(value);
|
|
break;
|
|
|
|
case 2:
|
|
printf("Enter value to delete: ");
|
|
scanf("%d", &value);
|
|
delete_value(value);
|
|
break;
|
|
|
|
case 3:
|
|
display();
|
|
break;
|
|
|
|
case 4:
|
|
exit(0);
|
|
|
|
default:
|
|
printf("Invalid choice\n");
|
|
}
|
|
}
|
|
}
|