5-51 两个有序链表序列的合并 (20分)
已知两个非降序链表序列S1与S2,设计函数构造出S1与S2的并集新非降序链表S3。
输入格式:
输入分两行,分别在每行给出由若干个正整数构成的非降序序列,用-1−1表示序列的结尾(-1−1不属于这个序列)。数字用空格间隔。
输出格式:
在一行中输出合并后新的非降序链表,数字间用空格分开,结尾不能有多余空格;若新链表为空,输出NULL。
输入样例:
1 3 5 -1
2 4 6 8 10 -1
输出样例:
1 2 3 4 5 6 8 10
#include<stdio.h>
#include<stdlib.h>
struct Node{
int num;
struct Node *next;
};
typedef struct Node * PNODE;
PNODE read()/*读入数据*/
{
PNODE t,pTile,phead = (PNODE)malloc(sizeof(struct Node));
phead->next = NULL;
pTile = phead;
int number;
do
{
scanf("%d",&number);
if(number != -1)
{
PNODE pnew = (PNODE)malloc(sizeof(struct Node));
pnew->num = number;
pnew->next = NULL;
pTile->next = pnew;
pTile = pnew;
}
}while(number != -1);
t = phead;
phead = t->next;
free(t);/*删除临时头结点*/
return phead;
}
void Attach(int number,PNODE * prear)
{
PNODE pnew = (PNODE)malloc(sizeof(struct Node));
pnew->num = number;
pnew->next = NULL;
(*prear)->next = pnew;
*prear = pnew;
}
PNODE combination(PNODE p1,PNODE p2)/*将p1,p2按非降序一个一个接上*/
{
PNODE t,rear,p = (PNODE)malloc(sizeof(struct Node));
p->next = NULL;
rear = p;
while(p1 && p2)
{
if(p1->num > p2->num)
{
Attach(p2->num,&rear);
p2 = p2->next;
}
else if(p1->num == p2->num)/*当数相等时,要将p1,p2的数都接入,非降序列每项不一定严格大于它的前一项,例如 1,1,1*/
{
Attach(p1->num,&rear);
Attach(p2->num,&rear);
p1 = p1->next;
p2 = p2->next;
}
else
{
Attach(p1->num,&rear);
p1 = p1->next;
}
}
while(p1)
{
Attach(p1->num,&rear);
p1 = p1->next;
}
while(p2)
{
Attach(p2->num,&rear);
p2 = p2->next;
}
t = p;
p = p->next;
free(t);
return p;
}
void print(PNODE p)/*输出*/
{
if(!p)
{
printf("NULL");
return;
}
int flag = 0;
while(p)
{
if(flag == 0)
{
printf("%d",p->num);
flag = 1;
}
else
{
printf(" %d",p->num);
}
p = p->next;
}
printf("\n");
}
int main(void)
{
PNODE p1,p2,p;
p1 = read();
p2 = read();
p = combination(p1,p2);
print(p);
return 0 ;
}
时间限制:1500ms内存限制:128MB代码长度限制:16kB判题程序:系统默认作者:DS课程组单位:浙江大学
转载请注明原文地址: https://ju.6miu.com/read-965747.html