Thursday, March 4, 2010

ds-operation on multi link list

//creating multi link list
//insert and delete operation is done based on ascending order
#include
#include
#include
typedef struct node
{
char name[20];
int age;
struct node *link1;
struct node *link2;
}node;

void ins_beg(node **,node **);
void insert(node **,node **);
void del_name(node **,node **);
void display_name(node *);
void display_age(node *);
void main()
{
node *head1=NULL,*head2=NULL;
int cmd;
clrscr();

while(cmd!=0)
{
printf("\nEnter Command-Insert(1),Display(Name Sorted)(2),Display(Age Sorted)(3),Quit(0)\n>");
scanf("%d",&cmd);
if(cmd==1)
insert(&head1,&head2);
else if(cmd==2)
display_name(head1);
else if(cmd==3)
display_age(head2);
else if(cmd==4)
del_name(&head1,&head2);
else
printf("\nInvalid Command!");
}

getch();
}

void insert(node **head1,node **head2)
{
node *newnode=(node *)malloc(sizeof(node));
node *p=NULL,*p1=NULL,*q=NULL,*q1=NULL;
if(newnode==NULL)
{
printf("\nMemory Overflow!");
return;
}
printf("\nEnter Name and Age: ");
scanf("%s%d",newnode->name,&newnode->age);
if(*head1==NULL && *head2==NULL)
{
newnode->link1=NULL;
newnode->link2=NULL;
*head1=*head2=newnode;
}
else
{ p=*head1;q=*head2;
while((p!=NULL) && strcmp(newnode->name,p->name)>0)
{
p1=p;
p=p->link1;
}
while((q!=NULL) && (newnode->age>q->age))
{
q1=q;
q=q->link2;
}
if(p1==NULL)
*head1=newnode;
else
p1->link1=newnode;
newnode->link1=p;
if(q1==NULL)
*head2=newnode;
else
q1->link2=newnode;
newnode->link2=q;
}
}

void ins_beg(node **head1,node **head2)
{
char ch;
do
{
node *newnode=(node *)malloc(sizeof(node));
if(newnode==NULL)
{
printf("\nMemory Overflow!");
return;
}
printf("\nEnter Name and Age : ");
scanf("%s%d",newnode->name,&newnode->age);
newnode->link1=*head1;
newnode->link2=*head2;
*head1=*head2=newnode;

fflush(stdin);
printf("\nDo You Want to continue(Y/N)>");

scanf("%c",&ch);
}while(ch=='y'||ch=='Y');
}

void display_name(node *head1)
{
printf("\nDisplaying result in sorted order of name:");
while(head1!=NULL)
{ printf("\nName=%s\tAge=%d",head1->name,head1->age);
head1=head1->link1;
}
}
void display_age(node *head2)
{
printf("\nDisplaying result in sorted order of age:");
while(head2!=NULL)
{ printf("\nName=%s\tAge=%d",head2->name,head2->age);
head2=head2->link2;
}
}

void del_name(node **head1,node **head2)
{
node *p=NULL,*q=NULL;
if(*head1==NULL)
{
printf("\nList is Empty!");
return;
}
p=*head1;
q=*head2;
if(p->link1==NULL && q->link2==NULL)
{
*head1=*head2=NULL;
return;
}
while(q->link2!=p)
{
q=q->link2;
}
if(q->link2==p)
q->link2=NULL;
else
q->link2=q->link2->link2;

(*head1)=p->link1;

free(p);

}

No comments:

Post a Comment