合并两个单链表

归纳编程学习的感悟,
记录奋斗路上的点滴,
希望能帮到一样刻苦的你!
如有不足欢迎指正!
共同学习交流!
🌎欢迎各位→点赞 👍+ 收藏⭐ + 留言​📝

但行前路,不负韶华!

cpp 复制代码
#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
#include<stdlib.h>
#include"LinkList.h"

#define DataType int 

LNode* MergeList(LinkList A, LinkList B);

int main()
{
	LinkList A, B, C;
	LNode* p;
	InitList(&A);
	InitList(&B);
	DataType a[] = { 12,16,21,33,35,87,102 };
	DataType b[] = { 3,5,21,23,35,99,123 };
	int n;
	n = sizeof(a) / sizeof(a[0]);
	for (int i = 1; i <=n; i++)
	{
		InsertElem(A, i, a[i - 1]);
	}
	n = sizeof(b) / sizeof(b[0]);
	for (int i = 1; i <= n; i++)
	{
		InsertElem(B, i, b[i - 1]);
	}
	printf("链表A中共有%d个元素:\n", ListLength(A));
	p = A->next;
	for (int i = 1; i <= ListLength(A); i++)
	{
		printf("%d ", p->data);
		p = p->next;
	}
	printf("\n");
	printf("链表B中共有%d个元素:\n", ListLength(B));
	p = B->next;
	for (int i = 1; i <= ListLength(B); i++)
	{
		printf("%d ", p->data);
		p = p->next;
	}
 	printf("\n");
	C = MergeList(A, B);
	printf("合并的链表C中共有%d个元素:\n", ListLength(C));
	p = C->next;
	for (int i = 1; i <= ListLength(C); i++)
	{
		printf("%d ", p->data);	
		p = p->next;
	}
	printf("\n");
	return 0;
}

LNode* MergeList(LinkList A, LinkList B)
{
	LinkList C;
	InitList(&C);
	LNode* temp;
	A = A->next;
	B = B->next;
	while (A && B)
	{
		if (A->data < B->data)
		{	
			InsertElemF(C, A->data);
			A = A->next;
		}
		else if(A->data==B->data)
		{
			temp = B;
			B = B->next;
			free(temp);
		}
		else
		{	
			InsertElemF(C, B->data);
			B = B->next;
		}
	}
	while (A)
	{
		InsertElemF(C, A->data);
		A = A->next;
	}
	while (B)
	{
		InsertElemF(C, B->data);
		B = B->next;
	}
	return C;
}
相关推荐
三克的油2 小时前
数据结构-4
数据结构
0566464 小时前
Python康复训练——数据结构
数据结构·windows·python
冻柠檬飞冰走茶4 小时前
PTA基础编程题目集 7-27 冒泡法排序(C语言实现)
c语言·开发语言·数据结构·算法
noipp7 小时前
推荐题目:洛谷 P5843 [SCOI2012] Blinker 的噩梦
c语言·数据结构·c++·算法·游戏·洛谷·luogu
冻柠檬飞冰走茶7 小时前
PTA基础编程题目集 7-20 打印九九口诀表(C语言实现)
c语言·开发语言·数据结构·算法
红叶舞8 小时前
基于线段树的数据结构
数据结构·python·算法
断点之下9 小时前
从“理扑克牌”到“分组优化”——直接插入排序与希尔排序详解
数据结构·算法·排序算法
起个破名想半天了9 小时前
算法与数据结构之DFS深度优先遍历
数据结构·算法·深度优先
鱼子星_9 小时前
【C++】深入剖析list:list及其双向迭代器实现
开发语言·数据结构·c++·笔记·stl·list
江屿风10 小时前
【C++笔记】【二叉搜索树】流食般投喂
开发语言·数据结构·c++·笔记