之前有实现过链表的定义和相关操作实现,可参考: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