已知两个非降序链表序列S1与S2,设计函数构造出S1与S2合并后的新的非降序链表S3。
输入格式:
输入分两行,分别在每行给出由若干个正整数构成的非降序序列,用−1表示序列的结尾(−1不属于这个序列)。数字用空格间隔。
输出格式:
在一行中输出合并后新的非降序链表,数字间用空格分开,结尾不能有多余空格;若新链表为空,输出NULL。
输入样例:
1 3 5 -1
2 4 6 8 10 -1
输出样例:
1 2 3 4 5 6 8 10
代码长度限制
16 KB
时间限制
1500 ms
内存限制
128 MB
#include <iostream>
using namespace std;
typedef struct Lnode
{
int data;
struct Lnode *next;
} Lnode, *Linklist;
int creat(Linklist &L)
{
L = new Lnode;
L->next = NULL;
Linklist p, q = L;
while (1)
{
p = new Lnode;
cin >> p->data;
if (p->data == -1)
{
return 0;
}
p->next = NULL;
q->next = p;
q = p;
}
}
void cmp(Linklist &L, int e)
{
Linklist p = L;
if ( p->next == NULL ||e < p->next->data )
{
Linklist q = new Lnode;
q->data = e;
q->next = p->next;
p->next = q;
}
else
{
while ( p->next != NULL && e >= p->next->data)
{
p = p->next;
}
Linklist q = new Lnode;
q->data = e;
q->next = p->next;
p->next = q;
}
}
void Print(Linklist L)
{
Linklist p = L->next;
if ( p == NULL )
{
cout << "NULL";
}
while (p != NULL)
{
cout << p->data;
if (p->next != NULL)
{
cout << " ";
}
p = p->next;
}
}
int main()
{
int t;
Linklist L;
creat(L);
while (1)
{
cin >> t;
if (t == -1)
{
break;
}
cmp(L, t);
}
Print(L);
return 0;
}