Sunday, February 27, 2011

Doubly

/*  Write a Program to create doubly linklist */

void first();
void last();
void disp();
void specific();
struct doubly
{
int info;
struct doubly *lptr,*rptr;
}*node,*l,*r,*p;

void main()
{
int item,choice,s1;
clrscr();
printf("Enter an item 99 for stop : ");
scanf("%d",&item);
node = (struct doubly *)malloc( sizeof(struct doubly));
l = r = p = node;
if(item == 99)
r = l = '\0';

while(item!=99)
{
node->info = item;

p->rptr = node; //This two line make left to right link
p = p->rptr;

node->lptr = r; //this three line make right to left link
// r->rptr = node;
r = node;

node->rptr = '\0';
node = (struct doubly *)malloc(sizeof(struct doubly));
scanf("%d",&item);
}

/* The above while loop will create doubly link list whose left node adress
is stored in l and right node address is stored in r */

l->lptr = '\0';
disp(); //Disp function is display left and right traversal.

do
{
printf("\n\n1 : Insert first.\n");
printf("2 : Insert Last.\n");
printf("3 : Insert Specific Position\n");
printf("4 : Exit from Program.\n");
printf("\nEnter Your Choice : ");
scanf("%d",&choice);
switch(choice)
{
case 1:
first();
disp();
break;
case 2 :
last();
disp();
break;
case 3 :
specific();
disp();
break;
case 4 :
exit();
default:
printf("\n\n\t\t######## INVALID CHOICE #########\n\n");
}
printf("\n\nDo you want to continue? if yes, press 1 : ");
scanf("%d",&s1);
}while(s1==1);
}




void disp()
{

p = l;
printf("\nLeft Traversal : ");
while(p!='\0')
{
printf("%d ",p->info);
p = p->rptr;
}

p = r;
printf("\nRight Traversal : ");
while(p!='\0')
{
printf("%d ",p->info);
p = p->lptr;
}

}

void first()
{
int item;
printf("Enter an integer value : ");
scanf("%d",&item);
node = (struct doubly *)malloc( sizeof(struct doubly));
node->lptr = '\0';
node->info = item;


node->rptr = l;
l->lptr = node;
l=node;
if(r == '\0')
r = l;

}
void last()
{
int item;
printf("Enter an integer value : ");
scanf("%d",&item);
node = (struct doubly *)malloc( sizeof(struct doubly));
node->rptr = '\0';
node->info = item;

node->lptr = r;
r->rptr = node;
r=node;
if(l=='\0')
l = r;


}


void specific()
{
int item,z,n=2;
printf("Enter an integer value : ");
scanf("%d",&item);
printf("Enter Position : ");
scanf("%d",&z);
node = (struct doubly *)malloc( sizeof(struct doubly));
node->info = item;
p = l;

if(z==1)
{
node->lptr = '\0';
node->rptr = l;
l->lptr = node;
l=node;
if(r=='\0')
r = l;
}
else
{
while(z>n)
{
p = p->rptr;
if(p == '\0')
{
printf("\n\n\t\tPosition is Not Found\n");
return;
}
z--;
}
if(p->rptr=='\0')
{
node->rptr = '\0';
p->rptr = node;
node->lptr = p;
p = node;
r = p;
}

else
{
p->rptr->lptr = node;
node->rptr = p->rptr;
p->rptr = node;
node->lptr = p;
}
}
}

No comments:

Post a Comment