PTA数据结构题编程题7-51 两个有序链表序列合并

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

输入格式:

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

输出格式:

在一行中输出合并后新的非降序链表,数字间用空格分开,结尾不能有多余空格;若新链表为空,输出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  ERROR   0
#define  OK            1

typedef int ElemType;
typedef struct LNode{
        ElemType Data;
        struct LNode * Next;
}LNode, * List;

List Create_L();
List CombineToL(List L1,List L2);

int main(){
        List L,L1,L2;
        int m,n,i;
        L1=Create_L();
        L2=Create_L();
        L=CombineToL(L1,L2);
        if(!L)
                printf("NULL");            //链表为空时
        else{
               while(L->Next){
                        printf("%d ",L->Data);
                        L=L->Next;
                }
                printf("%d",L->Data);
        }
        return 0;
}
List Create_L(){
        List head,L,pro;
        int n;
        L=(List)malloc(sizeof(LNode));
        head=L;
        scanf("%d",&n);
        if(n==-1){
                L=NULL;
                return L;
        }
        while(1){
                if(n==-1){                      //序列结束符号
                        pro->Next=NULL;         //序列尾指向NULL
                        free(L);                //释放多余节点
                        return head;
                }
                L->Data=n;
                L->Next=(List)malloc(sizeof(LNode));
               pro=L;
                L=L->Next;
                scanf("%d",&n);
        }
}
List CombineToL(List L1,List L2){
        List L,head;
        L=(List)malloc(sizeof(LNode));            //建立一个空节点,起到头结点的作用,便于后续拼接
        head=L;
        while(L1&&L2){
                if(L1->Data<=L2->Data){
                        L->Next=L1;
                        L=L->Next;
                        L1=L1->Next;
                }
                else{
                        L->Next=L2;
                        L=L->Next;L2=L2->Next;
                }
        }
        if(L1){                        //L2进行到空或者L2初始为空
                L->Next=L1;
                L=head;
                head=head->Next;
                free(L);
                return head;
        }
        else if(L2){                   //L1进行到空或者L1初始为空
                L->Next=L2;
                L=head;
                head=head->Next;
                free(L);
                return head;
        }
        else                            //两者初始皆为空
                return  NULL;
}

本题中,与之前文章( 见《链表操作---有序拼接》)中的要求大体相似, 区别体现在对于输入序列的要求不同 ,上篇中输入的两个序列长度是已知的,而此篇中为未知,遍历到输入数据为-1便结束序列。

猜你喜欢

转载自blog.csdn.net/youm3872/article/details/80582696