链表----合并有序单链表

之前有实现过链表的定义和相关操作实现,可参考:https://blog.csdn.net/merry1996/article/details/95185387

在之前的基础上增加了新的合并两个链表的函数

typedef int Item;
typedef struct node
{
    Item item;
    struct node *next;
}Node;

typedef Node *List;
/*
 *将递增有序的单链表LA和LB合并成一个递增有序的单链表LC
 *LA和LB没有头结点
 */
List MergeList(List LA, List LB)
{
    List LC = NULL;//将LC初始置空表
    Node* rear;
    /*ptrA和ptrB分别指向两个单链表LA和LB中的第一个节点*/
    Node* ptrA = LA;
    Node* ptrB = LB;
    //决定LC的第一个节点
    if(ptrA->item <= ptrB->item)
    {
        LC = LA;
        ptrA = ptrA->next;
        LC->next = NULL;
    }
    else
    {
        LC = LB;
        ptrB = ptrB->next;
        LC->next = NULL;
    }
    //rear初始值为LC且rear始终指向LC的链尾
    rear = LC;
    //当两个表中均未处理完时,比较选择将较小值节点插入新表LC中
    while(ptrA != NULL && ptrB != NULL)
    {
        if(ptrA->item <= ptrB->item)
        {
            rear->next = ptrA;
            rear = ptrA;
            ptrA = ptrA->next;
            rear->next = NULL;

        }
        else
        {
            rear->next = ptrB;
            rear = ptrB;
            ptrB = ptrB->next;
            rear->next = NULL;
        }
    }
    //若表LA未完,将表LA中后续元素链到新表LC表尾
    //若表LB未完,将表LB中后续元素链到新表LC表尾
    if(ptrA)
    {
        rear->next = ptrA;
    }
    else
    {
        rear->next = ptrB;
    }
    return LC;
}

用来测试的main函数:

/*与list.c一起编译*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "list.h"
void show_values(Item item)
{
    printf("item:%d\n", item);
}
int main()
{
    List LA;
    List LB;
    List LC;
    Item temp;
    int ret;
    InitializeList(&LA);
    InitializeList(&LB);
    puts("create LA");

    while((ret = scanf("%d", &temp)) == 1)//当输入ctrl+Z时,scanf返回值为-1,循环退出
    {
        if(AddItem(temp, &LA) == false)
        {
            fprintf(stderr, "Problem allocating memory\n");
            break;
        }
    }
    Traverse(&LA, show_values);
    puts("create LB");
    while((ret = scanf("%d", &temp)) == 1)
    {
        if(AddItem(temp, &LB) == false)
        {
            fprintf(stderr, "Problem allocating memory\n");
            break;
        }
    }
    Traverse(&LB, show_values);

    puts("merge LA and LB");
    LC = MergeList(LA, LB);
    Traverse(&LC, show_values);
    return 0;
}

运行结果:

create LA
2 5 6 8
^Z
item:2
item:5
item:6
item:8
create LB
1 3 7 9 10 11
^Z
item:1
item:3
item:7
item:9
item:10
item:11
merge LA and LB
item:1
item:2
item:3
item:5
item:6
item:7
item:8
item:9
item:10
item:11

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值