两个有序链表序列的合并

本文探讨了如何高效地合并两个已排序的链表,通过介绍经典的递归和迭代解决方案,详细阐述了合并过程的关键步骤和时间复杂度分析。无论你是初学者还是经验丰富的开发者,都将从这篇关于链表操作的深入探讨中受益。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include <stdio.h>
#include <stdlib.h>
/** 习题2.5 两个有序链表序列的合并 (15 分)
 *
 * L1和L2是给定的带头结点的单链表,
 *其结点存储的数据是递增有序的;
 *函数Merge要将L1和L2合并为一个非递减的整数序列。
 *应直接使用原序列中的结点,
 *返回归并后的带头结点的链表头指针。
 *
 */

typedef int ElementType;
typedef struct Node *PtrToNode;
struct Node {
    ElementType Data;
    PtrToNode   Next;
};
typedef PtrToNode List;


List Read(){
    List head,pnew,ptail;
    pnew=(List)malloc(sizeof(struct Node));
    pnew->Next=NULL;
    head=pnew;
    ptail=pnew;
    int n,i=0;
    scanf("%d",&n);
    for(i;i<n;i++){
        pnew=(List)malloc(sizeof(struct Node));
        scanf("%d",&pnew->Data);
        ptail->Next=pnew;
        ptail=pnew;
        ptail->Next=NULL;
    }
    return head;
}
void Print( List L ){
    List p;
    for(p=L->Next;p;p=p->Next){
        printf("%d ",p->Data);
    }
    printf("\n");
}

List Merge( List L1, List L2 ){
    List CreatListhead;//标记头结点
    List pL1,PL2;
    CreatListhead=(List)malloc(sizeof(struct Node));
    CreatListhead->Next=NULL;
    List creatList=CreatListhead;//合并链表
    pL1=L1->Next;
    PL2=L2->Next;
    while(pL1&&PL2){
        if(pL1->Data<=PL2->Data){
            creatList->Next=pL1;
            creatList=pL1;
            pL1=pL1->Next;
            }
        else {
            creatList->Next=PL2;
            creatList=PL2;
            PL2=PL2->Next;
        }
    }

    if(pL1==NULL)
        creatList->Next=PL2;
    else if(PL2==NULL)
        creatList->Next=pL1;


    L1->Next=NULL;
    L2->Next=NULL;

    return CreatListhead;
}

int main()
{
    List L1, L2, L;
    L1 = Read();
    L2 = Read();
    L = Merge(L1, L2);
    Print(L1);
    Print(L2);
    Print(L);
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值