刚学链表...求教问题...
下面是一个合并2个链表的程序其中merge函数是不是有问题啊?
该怎么改啊?
#include <stdio.h>
#include <stdlib.h>
#define LINK struct link
LINK
{
int data;
LINK *next;
};
LINK *createLinkA(void)
{
int i = 1;
LINK *head = NULL,*p,*pr;
while (i < 6)
{
p = (LINK *)malloc(sizeof(LINK));
if(p==NULL)
exit(0);
p->data = i*10;
i++;
if(i == 2)
head = p;
else
pr->next = p;
pr = p;
}
p->next = NULL;
return (head);
}
LINK *creatLinkB(void)
{
int i = 1;
LINK *head = NULL,*p,*pr;
while (i < 6)
{
p = (LINK *)malloc(sizeof(LINK));
if(p==NULL)
exit(0);
p->data = i*10+5;
i++;
if(i == 2)
head = p;
else
pr->next = p;
pr = p;
}
p->next = NULL;
return (head);
}
void printLink(LINK *head)
{
int i = 0;
LINK *p;
p = head;
if(head == NULL)
printf("Link is empty!\n");
else
{
while (p != NULL)
{
printf("%10d%10d\n",i++,p->data);
p = p->next;
}
}
}
LINK *merge(LINK *A,LINK *B)
{
LINK *head = NULL,*p;
head= A;
p = head;
while (B != NULL)
{
while (A!=NULL&&((A->data)<(B->data)))
{
p = A;
A = A->next;
p = p->next;
p->next = NULL;
}
p = B;
B = B->next;
p = p->next;
p->next = NULL;
}
return head;
}
int main()
{
LINK *A,*B;
LINK *head = NULL;
A = createLinkA();
B = creatLinkB();
printf("The nodes of link A are:\n");
printLink(A);
printf("The nodes of link B are:\n");
printLink(B);
head=merge(A,B);
printLink(head);
system("pause");
return 0;
}