#include <stdio.
h>
#include <stdlib.h> // For malloc and exit
#include <string.h>
struct node {
int label;
struct node *next;
};
int main() {
int ch, found = 0, k;
struct node *h, *temp, *head, *h1;
// Head node construction
head = (struct node *)malloc(sizeof(struct node));
head->label = -1;
head->next = NULL;
while (1) {
printf("\n\nSINGLY LINKED LIST OPERATIONS\n");
printf("1 -> Add\n");
printf("2 -> Delete\n");
printf("3 -> View\n");
printf("4 -> Exit\n");
printf("Enter your choice: ");
scanf("%d", &ch);
switch (ch) {
case 1: // Add
printf("\nEnter label after which to add: ");
scanf("%d", &k);
h = head;
found = 0;
while (h != NULL) {
if (h->label == k) {
found = 1;
break;
}
h = h->next;
}
if (!found) {
printf("Node not found\n");
} else {
temp = (struct node *)malloc(sizeof(struct node));
printf("Enter label for new node: ");
scanf("%d", &temp->label);
temp->next = h->next;
h->next = temp;
printf("Node added successfully.\n");
}
break;
case 2: // Delete
printf("Enter label of node to be deleted: ");
scanf("%d", &k);
found = 0;
h = h1 = head;
while (h->next != NULL) {
if (h->next->label == k) {
found = 1;
break;
}
h = h->next;
}
if (!found) {
printf("Sorry, node not found\n");
} else {
temp = h->next;
h->next = temp->next;
free(temp);
printf("Node deleted successfully.\n");
}
break;
case 3: // View
printf("\n\nHEAD -> ");
h = head->next; // Skip dummy head
while (h != NULL) {
printf("%d -> ", h->label);
h = h->next;
}
printf("NULL\n");
break;
case 4:
printf("Exiting...\n");
exit(0);
default:
printf("Invalid choice\n");
}
}
return 0;
}