2-11. 两个有序链表序列的合并(15)
已知两个非降序链表序列S1与S2,设计函数构造出S1与S2的并集新非降序链表S3。
输入格式说明:
输入分2行,分别在每行给出由若干个正整数构成的非降序序列,用-1表示序列的结尾(-1不属于这个序列)。数字用空格间隔。
输出格式说明:
在一行中输出合并后新的非降序链表,数字间用空格分开,结尾不能有多余空格;若新链表为空,输出“NULL”。
样例输入与输出:
序号 | 输入 | 输出 |
1 |
1 3 5 -1 2 4 6 8 10 -1 |
1 2 3 4 5 6 8 10 |
2 |
1 2 3 4 5 -1 1 2 3 4 5 -1 |
1 1 2 2 3 3 4 4 5 5 |
3 |
-1 -1 |
NULL |
链表标准代码:
#include <stdio.h>
#include <stdlib.h>
#define LEN (struct node*)malloc(sizeof(struct node))
struct node
{
int num;
struct node *next;
};
node *creat()
{
node *t,*p,*head;
int n,i=0;
p=LEN;
t=p;
scanf("%d",&p->num);
head=NULL;
p->next=NULL;
while(p->num!=-1){
if(!i){
head=p;
i=1;
}
else
t->next=p;
t=p;
p=LEN;
scanf("%d",&p->num);
p->next=NULL;
}
return head;
}
node *he(node *head1,node *head2)
{
node *head,*t,*p1,*p2,*p,*w;
int flag=0;
head=NULL;
t=head;
p1=head1;
p2=head2;
while(p1&&p2){
p=LEN;
if(p1->num > p2->num)
{
p->num=p2->num;
p->next=NULL;
p2=p2->next;
if(!flag){
head=p;
flag=1;
}
else
t->next=p;
t=p;
}
else if(p1->num < p2->num)
{
p->num=p1->num;
p->next=NULL;
p1=p1->next;
if(!flag){
head=p;
flag=1;
}
else
t->next=p;
t=p;
}
else{
w=LEN;
p->num=w->num=p1->num;
p->next=w->next=NULL;
if(!flag){
head=p;
flag=1;
}
else
t->next=p;
t=p;
t->next=w;
t=w;
p1=p1->next;
p2=p2->next;
}
}
if(p1)
{
while(p1)
{
p=LEN;
p->num=p1->num;
p->next=NULL;
p1=p1->next;
if(!flag){
head=p;
flag=1;
}
else
t->next=p;
t=p;
}
}
else if(p2)
{
while(p2)
{
p=LEN;
p->num=p2->num;
p->next=NULL;
p2=p2->next;
if(!flag){
head=p;
flag=1;
}
else
t->next=p;
t=p;
}
}
return head;
}
void print(node *head)
{
struct node *p;
p=head;
int i=0;
while(p!=NULL){
if(i)
printf(" ");
i=1;
printf("%d",p->num);
p=p->next;
}
if(!i)
printf("NULL");
printf("\n");
}
int main()
{
node *head1,*head2;
head1=creat();
head2=creat();
head1=he(head1,head2);
print(head1);
return 0;
}
vector解法:
#include <stdio.h>
#include <algorithm>
#include <vector>
using namespace std;
vector < int > v;
int main()
{
int i,j=0,b;
for(i=0;i<2;i++){
for(;;){
scanf("%d",&b);
if(b==-1)
break;
v.push_back(b);
}
}
sort(v.begin(),v.end());
j=v.size();
if(!j)
printf("NULL\n");
else{
printf("%d",v[0]);
for(i=1;i<j;i++)
printf(" %d",v[i]);
printf("\n");
}
return 0;
}