Hello,
Following code works partially. I's trying to merge two lists into one lists so that their nodes in merged lists are exactly at alternative posistions.
Please let me know, where I am wrong. merge works fine is boths list have same number of nodes or first node has more nodes. But seems like does not work when second list has more nodes.
Code:
# include<stdio.h>
struct node
{
int data;
struct node *next;
};
void append(struct node **p,int num)
{
static struct node *temp;
if ( *p == NULL )
{
*p = (struct node *)malloc(sizeof(struct node));
temp = *p;
(*p)->next = NULL;
(*p)->data = num;
}
else
{
temp->next = (struct node *)malloc(sizeof(struct node));
temp = temp->next;
temp->data = num;
temp->next = NULL;
}
}
void display( struct node *p)
{
printf("\n\n");
while ( p != NULL )
{
printf("%d\t",p->data);
p = p->next;
}
}
struct node * mergelist(struct node **p,struct node **q)
{
struct node *saveP, *saveQ, *tempP, *tempQ;
tempP = *p;
tempQ = *q;
while ( tempP && tempQ )
{
saveP = tempP->next;
saveQ = tempQ->next;
if ( saveP && saveQ )
{
// if ( tempP != *p )
tempP->next = tempQ;
tempQ->next = saveP;
tempP = saveP->next;
saveP->next = saveQ;
tempQ = saveQ->next;
saveQ->next = tempP;
}
}
/*if ( tempP == 0)
tempP = tempQ;
else
tempQ = tempP;*/
return *p;
}
void main()
{
int val;
struct node *p,*q,*r;
p = q = r = NULL;
printf("\nCreate P list\n\n");
scanf("%d",&val);
while ( val)
{
append(&p,val);
scanf("%d",&val);
}
display(p);
printf("\n\nCreate Q list\n");
scanf("%d",&val);
while ( val)
{
append(&q,val);
scanf("%d",&val);
}
display(q);
r = mergelist(&p,&q);
display(r);
}