7-1 两个有序链表序列的合并(20 分)
已知两个非降序链表序列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
代码如下:
#include <stdio.h>
#include <stdlib.h>
#define TRUE 1
#define FALSE 0
#define OK 1
#define ERROR 0
#define INFEASIBLE -1
#define OVERFLOW -2
typedef int Status;
typedef int ElemType;
typedef struct LNode{
ElemType data;
struct LNode *next;
}LNode, *LinkList;
Status InitList(LinkList &L);
void ListPrint(LinkList L);
void ListRead(LinkList &L);
LinkList ListCombine(LinkList &L1,LinkList &L2,LinkList &L3);
Status InitList(LinkList &L)
{
L = (LNode*)malloc(sizeof(LNode));
if(!L)
exit(OVERFLOW);
L->next = NULL;
return OK;
}
Status ListInsert(LinkList &L)
{
LNode *curPtr, *rearPtr = L;
ElemType e;
scanf("%d", &e);
while(e > 0)
{
curPtr = (LNode*)malloc(sizeof(LNode));
if(!curPtr)
exit(OVERFLOW);
curPtr->data = e;
curPtr->next = NULL;
rearPtr->next = curPtr;
rearPtr = curPtr;
scanf("%d", &e);
if(e < 0)
rearPtr->next = NULL;
}
//rearPtr->next = NULL;
return OK;
}
void ListPrint(LinkList L)
{
LNode *p = L->next;
if(p == NULL)
{
printf("NULL");
return ;
}
while(p)
{
printf("%d ", p->data);
p = p->next;
}
}
LinkList ListCombine(LinkList &L1,LinkList &L2,LinkList &Lc)
{
LNode *La = L1->next;
LNode *Lb = L2->next;
LNode *L3;
L3 = Lc = L1;
while(La != NULL && Lb != NULL)
{
if(La->data > Lb->data)
{
L3->next = Lb;
Lb = Lb->next;
}
else if(La->data <= Lb->data)
{
L3->next = La;
La = La->next;
}
L3 = L3->next;
}
if(La != NULL)
L3->next = La;
else
L3->next = Lb;
return Lc;
}
int main()
{
LinkList L1, L2, L3;
InitList(L1);
InitList(L2);
InitList(L3);
ListInsert(L1);
ListInsert(L2);
ListCombine(L1,L2,L3);
ListPrint(L3);
return 0;
}
事实上在写的时候真的犯傻,因为一开始没有定义L3,直接把Lc输出了,但Lc最后是等于有一个链表为空时的第一个节点的位置,执行ListPrint(Lc)之后就是从一个链表为空时开始的,所以测试结果只会输出6 8 10.以上。