0% found this document useful (0 votes)
8 views3 pages

Singly C

The document contains a C program that implements a singly linked list with operations to add, delete, and view nodes. It includes a main menu for user interaction and manages memory allocation for nodes. The program continues to run until the user chooses to exit.

Uploaded by

akshaya31032007
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views3 pages

Singly C

The document contains a C program that implements a singly linked list with operations to add, delete, and view nodes. It includes a main menu for user interaction and manages memory allocation for nodes. The program continues to run until the user chooses to exit.

Uploaded by

akshaya31032007
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 3

#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;
}

You might also like