C Programming language

adplus-dvertising
C - Doubly Linked List, Insertion
Previous Home Next

Program to insert node in a doubly linked list that shows how to perform various insertion operations on the linked list.

#include<stdio.h>
#include<conio.h>
#include<malloc.h>
#include<process.h>
struct node
    {
int num;
struct node *next;
struct node *prev;
};                           /* declaring a global node of type struct */
typedef struct node NODE;   /* providing a type definition to the above created structure */
NODE *head=NULL; /* declaring some of the global variable that would be used throughout the program */
NODE *temp, *first, last;
int info;
void display();
void insert_at_end();
void insert_at_begin();
void insert_at_specifiedpos();
void main()            /* starting the main method() */
{
int i;
clrscr();
printf("\nprogram for insertion in a doubly linked list :\n");
do
{
printf("\nEnter your choice :\n");
printf("\n1.Insert element at the end of the linkedlist :");
printf("\n2.Insert element at the begin of the linkedlist :");
printf("\n3.Insert at any specified position in the linkedlist :");
printf("\n4.Exit\n");
fflush(stdin);
scanf("\n%d",&i);
switch(i)
{
case 1:
insert_at_end();
display();
break;
case 2:
insert_at_begin();
display();
break;
case 3:
insert_at_specifiedpos();
display();
break;
case 4:
exit(0);
}
}
while(i<=4);
getch();
}
void insert_at_end()
{
printf("\nEnter your element in the linked list :");
scanf("%d",&info);
temp=(NODE *)malloc(sizeof(NODE));   /* allocating memory for the node to be inserted */
temp->num=info;
temp->next=NULL;
temp->prev=NULL;
if(head==NULL)                      /* checking whether list is empty */
{
head=temp;
first=temp;
last=temp;
}
else
{
first=head;
while(first->next!=last)
{
first=first->next;
}
first->next=temp;
temp->prev=first;
temp->next=NULL;
last=temp;
}
}
void display()
{
first=head;
printf("\nStatus of the doubly linked list is as follows :\n");
while(first->next!=NULL)                  /* traversing the linked list */
{
printf("\n%d",first->num);
first=first->next;
}
}
void insert_at_begin()
{
printf("\nEnter the value which do you want to insert at begining\n");
scanf("\n%d"&info);
temp=(NODE *)malloc(sizeof(NODE));
temp->num=info;
temp->next=NULL;
temp->prev=NULL;
if(head=NULL)
{
head=temp;
last=temp;
}
else
{
temp->next=head;
head->prev=temp;
temp->prev=NULL
head=temp;
}
}
void insert_at_specifiedpos()
{
NODE *second;
int node_num,info;
int i=1;
printf("\nEnter the nodenumber after which you want to insert new node\n");
scanf("%d",&node_num);
printf("\nEnter the value of new node\n");
scanf("\n%d",&info);
temp=(NODE *)malloc(sizeof(NODE));
temp->num=info;
temp->next=NULL;
temp->prev=NULL;
first=head;
while(i<node_num)
{
second=first;
first=first->next;
}
temp->next=first;
temp->prev=second;
first->prev=temp;
second->next=temp;

}
}
Previous Home Next