C Program to implement Singly Linked List to insert and delete a node from rear and display the contents of the Singly List
Program
#include<stdio.h>
#include<malloc.h>
#include<stdlib.h>
struct node
{
int info;
struct node *link;
};
typedef struct node* NODE;
NODE getnode();
NODE insert_rear(NODE , int);
NODE delete_rear(NODE);
void display(NODE);
void main()
{
NODE first;
int choice, item;
first = NULL;
for(;;)
{
printf("Enter\n");
printf("1. Insert Rear\n");
printf("2. Delete Rear\n");
printf("3. Display the list\n");
printf("4. Exit\n");
scanf("%d", &choice);
switch(choice)
{
case 1:
printf("\nEnter item to be inserted\n");
scanf("%d", &item);
first = insert_rear(first, item);
break;
case 2:
first = delete_rear(first);
break;
case 3:
display(first);
break;
default:
exit(0);
}
}
}
NODE getnode()
{
NODE x;
x = (NODE) malloc(sizeof(struct node));
if(x == NULL)
{
printf("Node creation error\n");
return;
}
return x;
}
NODE insert_rear(NODE first , int item)
{
NODE temp, current;
temp = getnode();
temp->info = item;
temp->link = NULL;
if(first == NULL)
{
return temp;
}
current = first;
while(current->link != NULL)
{
current = current->link;
}
current->link = temp;
return first;
}
NODE delete_rear(NODE first)
{
NODE current, prev;
if (first == NULL)
{
printf("Cannot delete. List is empty\n");
return first;
}
if(first->link == NULL)
{
printf("Deleted item is %d\n", first->info);
free(first);
first = NULL;
return first;
}
current = first;
prev = NULL;
while(current->link != NULL)
{
prev = current;
current = current->link;
}
printf("Deleted item is %d\n", current->info);
free(current);
prev->link = NULL;
return first;
}
void display(NODE first)
{
NODE temp;
printf("Contents of linked list is:\n");
if(first == NULL)
{
printf("Empty LIST\n");
return;
}
temp = first;
while(temp != NULL)
{
printf("%d\n", temp->info);
temp = temp->link;
}
}
Output
Enter
1. Insert Rear
2. Delete Rear
3. Display the list
4. Exit
1
Enter item to be inserted
10
Enter
1. Insert Rear
2. Delete Rear
3. Display the list
4. Exit
1
Enter item to be inserted
20
Enter
1. Insert Rear
2. Delete Rear
3. Display the list
4. Exit
3
Contents of linked list is:
10 20
Enter
1. Insert Rear
2. Delete Rear
3. Display the list
4. Exit
1
Enter item to be inserted
30
Enter
1. Insert Rear
2. Delete Rear
3. Display the list
4. Exit
3
Contents of linked list is:
10 20 30
Enter
1. Insert Rear
2. Delete Rear
3. Display the list
4. Exit
2
Deleted item is 30
Enter
1. Insert Rear
2. Delete Rear
3. Display the list
4. Exit
2
Deleted item is 20
Enter
1. Insert Rear
2. Delete Rear
3. Display the list
4. Exit
3
Contents of linked list is:
10
Enter
1. Insert Rear
2. Delete Rear
3. Display the list
4. Exit
2
Deleted item is 10
Enter
1. Insert Rear
2. Delete Rear
3. Display the list
4. Exit
2
Cannot delete. List is empty
Enter
1. Insert Rear
2. Delete Rear
3. Display the list
4. Exit
3
Empty LIST
Enter
1. Insert Rear
2. Delete Rear
3. Display the list
4. Exit
4