合并两个单链表

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

但行前路,不负韶华!

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;
}
相关推荐
Fanxt_Ja2 天前
【LeetCode】算法详解#15 ---环形链表II
数据结构·算法·leetcode·链表
今后1232 天前
【数据结构】二叉树的概念
数据结构·二叉树
散1123 天前
01数据结构-01背包问题
数据结构
消失的旧时光-19433 天前
Kotlinx.serialization 使用讲解
android·数据结构·android jetpack
Gu_shiwww3 天前
数据结构8——双向链表
c语言·数据结构·python·链表·小白初步
苏小瀚3 天前
[数据结构] 排序
数据结构
睡不醒的kun3 天前
leetcode算法刷题的第三十四天
数据结构·c++·算法·leetcode·职场和发展·贪心算法·动态规划
吃着火锅x唱着歌3 天前
LeetCode 978.最长湍流子数组
数据结构·算法·leetcode
Whisper_long3 天前
【数据结构】深入理解堆:概念、应用与实现
数据结构
IAtlantiscsdn3 天前
Redis7底层数据结构解析
前端·数据结构·bootstrap