合并单向有序列表

#include <stdio.h>
#include <stdlib.h>
typedef int ElementType;
typedef struct Node *PtrToNode;
typedef struct Node {
    ElementType Data;
    PtrToNode   Next;
};
typedef PtrToNode List;//链表指针


List Read();
void Print( List L );
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=0,i=0;
int x;
scanf("%d",&N);
PtrToNode head;//尾插法需要一个开始指向头部的指针
PtrToNode tail;
head=(PtrToNode)malloc(sizeof(struct Node));
head->Next=NULL;
tail=head;
for(i=0;i<N;i++)
{
scanf("%d",&x);
PtrToNode templeNode;
templeNode=(PtrToNode)malloc(sizeof(struct Node));
templeNode->Data=x;
tail->Next=templeNode;//将当前尾部的指针指向新节点
tail=templeNode;//将新节点作为尾部
}
tail->Next=NULL;
return head;
}
void Print(List tmp)
{
    PtrToNode p=tmp;
    if(!(p->Next))
    {
        printf("NULL");
    }
    while(p->Next)
    {
        printf("%d ",p->Next->Data);
        p=p->Next;
    }
    printf("\n");
}
List Merge( List L1, List L2 )
{
    PtrToNode newListhead,newListtail;
    newListhead=(PtrToNode)malloc(sizeof(struct Node));
    newListhead->Next=NULL;
    newListtail=newListhead;
    while(L1->Next!=NULL&&L2->Next!=NULL)//首先循环两个元素都非空的部分
    {
        if(L1->Next->Data<=L2->Next->Data)
        {
            newListtail->Next=L1->Next;//将L1的元素查入到新表
            newListtail=L1->Next;//改变新表尾
            L1->Next=newListtail->Next;//将L1的表向后移动
        }
        else
        {
            newListtail->Next=L2->Next;
            newListtail=L2->Next;
            L2->Next=newListtail->Next;
        }
    }
    if(L1->Next==NULL)
    {
        while(L2->Next!=NULL)
        {
            newListtail->Next=L2->Next;
            newListtail=L2->Next;
            L2->Next=newListtail->Next;
        }
    }
    if(L2->Next==NULL)
    {
        while(L1->Next!=NULL)
            {
                newListtail->Next=L1->Next;
                newListtail=L1->Next;
                L1->Next=newListtail->Next;
            }
    }
    newListtail->Next=NULL;
    return newListhead;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值