C Program to implement Doubly Linked List to insert and delete a node from front and display the contents of the Doubly Linked List
Program
#include<stdio.h>
#include<malloc.h>
#include<stdlib.h>
struct node
{
int info;
struct node *rlink;
struct node *llink;
};
typedef struct node* NODE;
NODE getnode();
NODE insert_front(NODE , int);
NODE delete_front(NODE);
void display(NODE);
void main()
{
NODE first;
int item, choice;
while(1)
{
printf("\n");
printf("1. Insert front\n");
printf("2. Delete front\n");
printf("3. Display\n");
printf("4. Exit\n");
scanf("%d",&choice);
switch(choice)
{
case 1:
printf("Enter item to be inserted\t");
scanf("%d", &item);
first = insert_front(first, item);
break;
case 2:
first = delete_front(first);
break;
case 3:
display(first);
break;
default:
exit(0);
}
}
}
NODE getnode()
{
NODE x;
x = (NODE) malloc(sizeof(struct node));
if(x == NULL)
{
printf("Unable to create node\n");
return;
}
return x;
}
NODE insert_front(NODE first, int item)
{
NODE temp;
temp = getnode();
temp->info = item;
temp->llink = NULL;
if(first == NULL)
return temp;
temp->rlink = first;
first->llink = temp;
return temp;
}
NODE delete_front(NODE first)
{
NODE next;
if(first == NULL)
{
printf("List is empty\n");
return first;
}
if(first->rlink == NULL && first->llink == NULL)
{
printf("Deleted item is: %d\n", first->info);
free(first);
return NULL;
}
next = first->rlink;
printf("Deleted item is: %d\n",first->info);
free(first);
return next;
}
void display(NODE first)
{
NODE temp;
if(first == NULL)
printf("List is empty\n");
printf("Contents of linked list:\n");
temp = first;
while(temp != NULL)
{
printf("%d\n", temp->info);
temp = temp->rlink;
}
}
Output
1. Insert front
2. Delete front
3. Display
4. Exit
2
List is empty
1. Insert front
2. Delete front
3. Display
4. Exit
1
Enter item to be inserted 40
1. Insert front
2. Delete front
3. Display
4. Exit
1
Enter item to be inserted 22
1. Insert front
2. Delete front
3. Display
4. Exit
1
Enter item to be inserted 31
1. Insert front
2. Delete front
3. Display
4. Exit
3
Contents of linked list:
31
22
40
1. Insert front
2. Delete front
3. Display
4. Exit
2
Deleted item is: 31
1. Insert front
2. Delete front
3. Display
4. Exit
2
Deleted item is: 22
1. Insert front
2. Delete front
3. Display
4. Exit
3
Contents of linked list:
40
1. Insert front
2. Delete front
3. Display
4. Exit
4