Saturday 13 December 2014

wap to implement doubly linked list

wap to implement doubly linked list

#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
typedef struct node
{
int data;
struct node *next,*prev;
}node;
void main()
{
int i,n,ch,loc,x;
node *head,*p,*q;
char c;
clrscr();
printf("N=");
scanf("%d",&n);
head=(node *)malloc(sizeof(node));
printf("\n\nEnter data of the nodes=");
scanf("%d",&head->data);
head->next=NULL;
head->prev=NULL;
p=head;
for(i=1;i<n;i++)
{
p->next=(node *)malloc(sizeof(node));
q=p;
p=p->next;
scanf("%d",&p->data);
p->prev=q;
p->next=NULL;
}
p=head;
printf("The linked list is=\nHead ");
while(p!=NULL)
{
printf(" -><-%d",p->data);
p=p->next;
}
do
{
printf("\n\n1.Insertion\t2.Deletion\n");
printf("Enter your choice=");
scanf("%d",&ch);
if(ch==1)
{
printf("\n\nEnter the location on which element to be inserted=");
scanf("%d",&loc);
printf("\nEnter the data to be inserted=");
scanf("%d",&x);
p=(node *)malloc(sizeof(node));
p->data=x;
p->next=NULL;
p->prev=NULL;
if(loc==1)
{
p->next=head;
head->prev=p;
head=p;
n++;
}
else if(loc==n)
{
q=head;
while(q->next!=NULL)
q=q->next;
q->next=p;
p->prev=q;
n++;
}
else if(loc>1&&loc<n)
{
q=head;
for(i=1;i<loc-1;i++)
q=q->next;
p->next=q->next;
p->prev=q;
q->next=p;
p->next->prev=p;
}
else
{
printf("\nInsertion not possible.");
}
p=head;
printf("The linked list is=\nHead ");
while(p!=NULL)
{
printf(" -><-%d",p->data);
p=p->next;
}
}
else if(ch==2)
{
printf("\n\nEnter the location to be deleted=");
scanf("%d",&loc);
p=head;
if(loc==1)
{
p->next->prev=NULL;
head=head->next;
free(p);
n--;
}
else if(loc==n)
{
while(p->next!=NULL)
p=p->next;
p->prev->next=NULL;
free(p);
n--;
}
else if(loc>1&&loc<n)
{
for(i=1;i<loc;i++)
p=p->next;
p->prev->next=p->next;
p->next->prev=p->prev;
free(p);
}
else
{
printf("\nInvalid location.");
}
p=head;
printf("The linked list is=\nHead ");
while(p!=NULL)
{
printf(" -><-%d",p->data);
p=p->next;
}
}
else
{
printf("\nSorry.");
}
printf("\n\nDo you  want to continue=");
c=getche();
}
while(c=='Y'||c=='y');
getch();
}

No comments:

Post a Comment