已知两个非降序链表序列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
对于这道题我一共有两个错误点。
可能大多数人和我错的一样,我的整体思路就是:再序列1和序列2的next都不为空时进行比较大小;然后当其中一个走到终点时,把另一个序列剩下的元素全都搬进新序列中。
易错点:
1、
if (s1->data < s2->data)
{
s3->next = s1;
s1 = s1->next;
s3 = s3->next;
}
else
{
s3->next = s2;
s2 = s2->next;
s3 = s3->next;
}
在判断时要用if。。。else。。。
不能把所有的情况都写出来,因为很可能就造成位置颠倒比如题中的例子,很可能的错误输出为 1 2 3 5 4 6 8 10;
2、
在判断链表是否为空时(设链表p)
有头节点时判断条件为(!p->next)
没有头节点就是(!p)
#include <iostream>
#include<algorithm>
using namespace std;
typedef struct node
{
int data;
struct node *next;
}node,*ptr;
ptr creat(node* &l)
{
int n;
cin >> n;
/*
//头部插入法
while (n!=-1)
{
node* p = (node*)malloc(sizeof(node));
p->data=n;
//将新节点插入到头节点后面
p->next = l->next;
l->next = p;
cin >> n;
}
return l;
*/
//尾部插入法
node* r = l;
while (n!=-1)
{
node* p = (node*)malloc(sizeof(node));
p->data = n;
r->next = p;
r = r->next;
cin >> n;
}
r->next = NULL;
return l;
}
void show(node*& l)
{
node* p;//用于遍历;
p = l->next;
while (p->next != NULL)
{
cout << p->data << " ";
p = p->next;
}
cout << p->data << endl;
}
int main()
{
node* l1, * l2, * l3;
l1 = (node*)malloc(sizeof(node));
l1->next = NULL;
l2 = (node*)malloc(sizeof(node));
l2->next = NULL;
l1 = creat(l1);
l2 = creat(l2);
l3 = (node*)malloc(sizeof(node));
node* s1 = l1->next;
node* s2 = l2->next;
node* s3 = l3;
while (s1 && s2)
{
if (s1->data < s2->data)
{
s3->next = s1;
s1 = s1->next;
s3 = s3->next;
}
else
{
s3->next = s2;
s2 = s2->next;
s3 = s3->next;
}
}
while (s1)
{
s3->next = s1;
s1 = s1->next;
s3 = s3->next;
}
while (s2)
{
s3->next = s2;
s2 = s2->next;
s3 = s3->next;
}
if (!l3->next)
{
cout << "NULL";
}
else
{
show(l3);
}
}