Problem Description
已知两个非降序链表序列S1与S2,设计函数构造出S1与S2的并集新非降序链表S3。
Input Description
输入分两行,分别在每行给出由若干个正整数构成的非降序序列,用−1表示序列的结尾(−1不属于这个序列)。数字用空格间隔。
Output Description
在一行中输出合并后新的非降序链表,数字间用空格分开,结尾不能有多余空格;若新链表为空,输出NULL。
Sample Input
1 3 5 -1
2 4 6 8 10 -1
Sample Output
1 2 3 4 5 6 8 10
Hint
链表
我开始写的代码:
本来想写注释的但没有时间,期末在补吧······
#include <iostream>
using namespace std;
typedef struct LNode
{
int date;
struct LNode *next;
}LNode, *LinkList;
void InsterList(LinkList &S1)
{
LinkList p;
p = S1;
int n;
cin >> n;
while (n != -1)
{
LinkList s = (LinkList)malloc(sizeof(LNode));
s->date = n;
s->next = NULL;
p->next = s;
p = p->next;
cin >> n;
}
}
void PrintList(LinkList S)
{
LinkList p;
p = S->next;
if (p == NULL)
{
cout << "NULL" << endl;
}
else
{
int i = 0;
while (p != NULL)
{
if (i++ > 0)
{
cout << " ";
}
cout << p->date;
p = p->next;
}
cout << endl;
}
}
void SortLink(LinkList &S1, LinkList &S2, LinkList &S3)
{
LinkList pa, pb;
LinkList pc;
pa = S1->next;
pb = S2->next;
S3 = S1;
pc = S3;
while (pa && pb)
{
if (pa->date <= pb->date)
{
pc->next = pa;
pc = pa;
pa = pa->next;
}
else
{
pc->next = pb;
pc = pb;
pb = pb->next;
}
}
pc->next = pa ? pa : pb;
delete S2;
}
int main()
{
LinkList S1 = (LinkList)malloc(sizeof(LNode));
LinkList S2 = (LinkList)malloc(sizeof(LNode));
LinkList S3 = (LinkList)malloc(sizeof(LNode));
S1->next = NULL;
S2->next = NULL;
S3->next = NULL;
int n;
InsterList(S1);
InsterList(S2);
SortLink(S1, S2, S3);
PrintList(S3);
return 0;
}