02-线性结构1 两个有序链表序列的合并(15 分)


#include <stdio.h>
#include <stdlib.h>
#include<bits/stdc++.h>
using namespace std;
typedef int ElementType;
typedef struct Node *PtrToNode;
struct Node {
    ElementType Data;
    PtrToNode   Next;
};
typedef PtrToNode List;

List Read(); /* 细节在此不表 */
void Print( List L ); /* 细节在此不表;空链表将输出NULL */

List Merge( List L1, List L2 );

int main()
{
    List L1, L2, L;
    L1 = Read();
    L2 = Read();
    L = Merge(L1, L2);
    Print(L);
    Print(L1);
    Print(L2);
    return 0;
}
List Read()
{
    int n;
    cin>>n;
    List L=(List)malloc(sizeof(Node));
    L->Next=NULL;
    List now=L;
    while(n--)
    {
        if(now->Next==NULL)
        {
            List t=(List)malloc(sizeof(Node));
            cin>>t->Data;
            t->Next=NULL;
            now->Next=t;
            now=t;

        }
    }
    return L;
}
void Print( List L )
{
    if(L->Next==NULL)
    {
        cout<<"NULL"<<endl;
        return;
    }
    List t=L->Next;
    while(t)
    {
        cout<<t->Data<<" ";
        t=t->Next;
    }
    cout<<endl;
}
List Merge( List L1, List L2 )
{
    List L3=(List)malloc(sizeof(Node));
    List L=L3;
    List p=L1->Next;
    List q=L2->Next;
    while(p&&q)
    {
        if(p->Data<q->Data)
        {
            L->Next=p;
            p=p->Next;
        }
        else
        {
            L->Next=q;
            q=q->Next;
        }
        L=L->Next;
    }
    L->Next=NULL;
    if(p) L->Next=p;
    if(q) L->Next=q;
    L1->Next=NULL;
    L2->Next=NULL;
    return L3;
}
需要注意的是这里的三个链表的头结点都是空的,只是在输出把头结点去掉了

猜你喜欢

转载自blog.csdn.net/Wchenchen0/article/details/80054601