Wednesday, April 1, 2009

Double linked list

/* DOUBLE LINKEDLIST*/
#include
#include
#include
#include
#define newnode (struct node *)malloc(sizeof(struct node ))
struct node
{
struct node *llink;
int info;
struct node *rlink;
};
struct node *p,*head,*q;
void insert(int pos,int val)
{
int ind=1;
q=newnode;
q->info=val;
p=head;
if(pos==1)
{
if(head==NULL)
{
q->rlink=NULL;
q->llink=NULL;
head=q;
}
else
{
q->rlink=p;
p->llink=q;
head=q;
}
}
else
{
while((ind!=pos-1)&&(p->rlink!=NULL))
{
p=p->rlink;
ind++;
}
if(p->rlink==NULL && ind!=pos-1)
{
printf(" \n The position is NOT Valid ");
}
else
{
q->rlink=p->rlink;
p->rlink->llink=q;
p->rlink=q;
q->llink=p;
}
}
}
void delet(int pos)
{
int ind=1;
struct node *temp;
p=head;
if(head==NULL)
printf(" List is empty ");
else
{
if(pos==1)
{
if(p->rlink==NULL)
{
free(p);
head=NULL;
}
else
{
temp=p;
p=p->rlink;
head=p;
p->llink=NULL;
free(temp);
}
}
else
{
while(ind!=pos-1 && p->rlink!=NULL)
{
p=p->rlink;
ind++;
}
if(p->rlink!=NULL)
{
temp=p->rlink;
p->rlink=p->rlink->rlink;
p->rlink->llink=p;
free(temp);
}
else
{
printf(" \n The position is NOT Valid ");
}
}
}
}
void display()
{
p=head;
if(p==NULL)
printf(" list is empty");
else
{
printf("\n ");
while(p!=NULL)
{
printf("\t%d",p->info);
p=p->rlink;
}
}
}
void main()
{
int op=99;
int post,v;
head=NULL;
while(1)
{
printf("\n Menu");
printf("\n1.insert");
printf("\n2.delete");
printf("\n3.display");
printf("\n4.exit");
printf("\n Enter U r choice..");
fflush(stdin);
scanf("%d",&op);
switch(op)
{
case 1:printf("\n Enter the pos&val to insert");
fflush(stdin);
scanf("%d%d",&post,&v);
insert(post,v);
break;
case 2:printf("\n Enter the pos delete");
fflush(stdin);
scanf("%d",&post);
delet(post);
break;
case 3:display();
break;
case 4:exit(0);
}
}
}

No comments:

Post a Comment