Untitled
unknown
plain_text
a year ago
3.5 kB
6
Indexable
#include <stdio.h>
#include <stdlib.h>
typedef struct node {
int info;
struct node *next;
} NODE;
void ins_first(NODE *head, int data) {
NODE *newnode;
newnode = (NODE*)malloc(sizeof(NODE));
if (newnode == NULL) {
printf("\nMemory allocation failed!");
return;
}
newnode->info = data;
newnode->next = head->next;
head->next = newnode;
head->info++; // increment node count
printf("\nNode with info %d is inserted as the first node in the list", data);
}
void ins_last(NODE *head, int data) {
NODE *newnode, *temp;
newnode = (NODE*)malloc(sizeof(NODE));
if (newnode == NULL) {
printf("\nMemory allocation failed!");
return;
}
newnode->info = data;
newnode->next = NULL;
temp = head;
while (temp->next != NULL)
temp = temp->next;
temp->next = newnode;
head->info++; // increment node count
printf("\nNode with info %d is inserted as the last node in the list", data);
}
void del_first(NODE *head) {
NODE *temp;
if (head->next == NULL) {
printf("\nEmpty List");
} else {
temp = head->next;
head->next = temp->next;
printf("\nFirst node with info %d is deleted", temp->info);
head->info--; // decrement node count
free(temp);
}
}
void del_last(NODE *head) {
NODE *temp, *prev;
if (head->next == NULL) {
printf("\nEmpty List");
} else {
prev = head;
temp = head->next;
while (temp->next != NULL) {
prev = temp;
temp = temp->next;
}
prev->next = NULL;
printf("\nLast Node with info %d is deleted", temp->info);
head->info--; // decrement node count
free(temp);
}
}
void display(NODE *head) {
NODE *temp;
if (head->next == NULL) {
printf("\nEmpty List");
return;
}
printf("\nList Contents:\nBegin->");
temp = head->next;
while (temp != NULL) {
printf("%d->", temp->info);
temp = temp->next;
}
printf("End");
printf("\nTotal number of nodes = %d", head->info);
}
int main() {
NODE *head;
int choice, data;
head = (NODE*)malloc(sizeof(NODE));
if (head == NULL) {
printf("\nMemory allocation failed!");
return 1;
}
head->info = 0; // initialize the node count
head->next = NULL;
while (1) {
printf("\n\n1: Ins@first\n2: Ins@last\n3: Del@first\n4: Del@last\n5: Display\n6: Exit");
printf("\nEnter your choice: ");
scanf("%d", &choice);
switch (choice) {
case 1:
printf("\nEnter the data to be inserted: ");
scanf("%d", &data);
ins_first(head, data);
break;
case 2:
printf("\nEnter the data to be inserted: ");
scanf("%d", &data);
ins_last(head, data);
break;
case 3:
del_first(head);
break;
case 4:
del_last(head);
break;
case 5:
display(head);
break;
case 6:
exit(0);
default:
printf("\nInvalid choice");
}
}
return 0;
}
Editor is loading...
Leave a Comment