已有a,b两个链表,每个链表中的结点包括学号、成绩。要求把两个链表合并,并且按学号升序排列。注:输入一个链表结束后,输入0表示结束;
注意输入输出格式。
【输入样例】
101,89
103,67
105,97
107,88
0
100,100
102,65
106,60
0
【输出样例】
100 100
101 89
102 65
103 67
105 97
106 60
107 88
#include<stdio.h>
#include<stdlib.h>
#define LEN sizeof(ListNode)
typedef struct lie
{
int num;
int score;
struct lie *next;
}ListNode;
ListNode *Creat()
{
ListNode *head,*p1,*p2;
p2=head=malloc(LEN);
head->next=NULL;
p1=malloc(LEN);
scanf("%d",&p1->num);
while(p1->num!=0)
{
scanf(",%d",&p1->score);
p1->next=NULL;
p2->next=p1;
p2=p1;
p1=malloc(LEN);
scanf("%d",&p1->num);
}
return head;
}
ListNode *Merge(ListNode *p1,ListNode *p2)
{
ListNode *h,*p,*q,*d;
h=malloc(LEN);//创建一个新的头节点
h->next=NULL;
p=p1->next;
q=p2->next;
d=h;
while(p&&q)//如果有一个为空指针,则跳出循环
{
if(p->num<q->num)//号码小的接在新的头指针后面
{
d->next=p;
p=p->next;
d=d->next;//使链表可以继续接下去
}
else
{
d->next=q;
q=q->next;
d=d->next;
}
}
if(p==NULL)//如果有一个为空指针,另一个就接在新链表的后面
d->next=q;
else
d->next=p;
DestroyList(p1);//销毁p1所指向的链表
DestroyList(p2);//销毁p2所指向的链表
return h;
}
void Output(ListNode *head)
{
ListNode *p;
p=head->next;
do
{
printf("%d %d\n",p->num,p->score);
p=p->next;
}while(p);
}
void DestroyList(ListNode *h)//销毁链表
{
ListNode *p;
while(h)
{
p=h;
h=h->next;
free(p);
}
}
int main()
{
ListNode *head1,*head2,*head;
head1=Creat();
printf("\n");
head2=Creat();
printf("\n");
head=Merge(head1,head2);
Output(head);
DestroyList(head);
return 0;
}