Hello Friends,
Today we discuss about Doubly Linked List Insertion Functions:
Function for insert at first Position or Insert at Beginning:
void insert_beg()
{
newnode=(struct node *)malloc(sizeof(struct node));
printf("\nEnter data:");
scanf("%d",&newnode->data);
newnode->next=head;
newnode->prev=NULL;
head->prev=newnode;
head=newnode;
}
Function for Insert at Specific Position or Insert In between:
void insert_spec()
{
struct node *a=head,*b=head;
int i,j,pos;
printf("\nEnter Position where you want to add NewNode:");
scanf("%d",&pos);
for(i=1; i<pos-1; i++)
{a=a->next;
}
newnode=(struct node *)malloc(sizeof(struct node));
printf("\nEnter data:");
scanf("%d",&newnode->data);
newnode->next=a->next;
newnode->prev=a;
a->next=newnode;
}
Function For Insert at Last Position:
void insert_last()
{
struct node *d=head;
newnode=(struct node*)malloc(sizeof(struct node));
printf("\nEnter data:");
scanf("%d",&newnode->data);
while(d->next!=NULL)
{d=d->next;}
d->next=newnode;
newnode->prev=d;
newnode->next=NULL;
}
Full Program for Insertion:
#include<stdio.h>
#include<stdlib.h>
struct node{
struct node *prev;
int data;
struct node *next;
};
struct node *head,*newnode,*temp,*disp;
void create()
{
int i,num;
printf("\nHow many Nodes you want to create:");
scanf("%d",&num);
for(i=1; i<=num; i++)
{
newnode=(struct node *)malloc(sizeof(struct node));
printf("\nEnter data:");
scanf("%d",&newnode->data);
if(head==NULL)
{
head=temp=newnode;
}else{
temp->next=newnode;
newnode->prev=temp;
newnode->next=NULL;
head->prev=NULL;
temp=temp->next;
}}}
void insert_beg()
{
newnode=(struct node *)malloc(sizeof(struct node));
printf("\nEnter data:");
scanf("%d",&newnode->data);
newnode->next=head;
newnode->prev=NULL;
head->prev=newnode;
head=newnode;
}
void insert_spec()
{
struct node *a=head,*b=head;
int i,j,pos;
printf("\nEnter Position where you want to add NewNode:");
scanf("%d",&pos);
for(i=1; i<pos-1; i++)
{a=a->next;
}
newnode=(struct node *)malloc(sizeof(struct node));
printf("\nEnter data:");
scanf("%d",&newnode->data);
newnode->next=a->next;
newnode->prev=a;
a->next=newnode;
}
void insert_last()
{
struct node *d=head;
newnode=(struct node*)malloc(sizeof(struct node));
printf("\nEnter data:");
scanf("%d",&newnode->data);
while(d->next!=NULL)
{d=d->next;}
d->next=newnode;
newnode->prev=d;
newnode->next=NULL;
}
void display()
{
disp=head;
while(disp!=NULL)
{
printf("%d->",disp->data);
disp=disp->next;
}
}
void main()
{
while(1)
{
int choice;
printf("\n1.Create, \n2.Display, \n3.Insert at first position, \n4.Insert at specific Position, \n5.Insert at last Position, \n6.Exit");
printf("\nEnter Choice:");
scanf("%d",&choice);
switch(choice)
{
case 1:
create();
break;
case 2:
display();
break;
case 3:
insert_beg();
break;
case 4:
insert_spec();
break;
case 5:
insert_last();
break;
case 6:
exit(0);
break;
default:
printf("\nInvalid Input");
break;
}
}
}
For Run Program With out any error use full Program.
No comments:
Post a Comment