7-1 两个有序链表序列的合并

来源:互联网 发布:17网广州网络批发市场 编辑:程序博客网 时间:2024/05/16 17:12

7-1 两个有序链表序列的合并(20 分)

已知两个非降序链表序列S1与S2,设计函数构造出S1与S2的并集新非降序链表S3。

输入格式:

输入分两行,分别在每行给出由若干个正整数构成的非降序序列,用1表示序列的结尾(1不属于这个序列)。数字用空格间隔。

输出格式:

在一行中输出合并后新的非降序链表,数字间用空格分开,结尾不能有多余空格;若新链表为空,输出NULL

输入样例:

1 3 5 -12 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  -2typedef 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;    }    return OK;}void ListPrint(LinkList L){    LNode *p = L->next;    if(p == NULL)    {        printf("NULL\n");        return ;    }    while(p)    {        printf("%d ", p->data);        p = p->next;    }}LinkList ListCombine(LinkList &L1,LinkList &L2,LinkList &L3){    LNode *La = L1->next;    LNode *Lb = L2->next;    LNode *Lc ;    L3 = Lc = L1;    while(La != NULL && Lb != NULL)    {        if(La->data > Lb->data)        {            Lc->next = Lb;            Lc = Lc->next;            Lb = Lb->next;        }        else if(La->data <= Lb->data)        {            Lc->next = La;            Lc = Lc->next;            La = La->next;        }    }   if(La!=NULL)Lc->next=La;   else Lc->next = Lb;    return L3;}int main(){    LinkList L1, L2, L3;    InitList(L1);    InitList(L2);    InitList(L3);    ListInsert(L1);    ListInsert(L2);    ListCombine(L1,L2,L3);    ListPrint(L3);    return 0;}


原创粉丝点击