链表的归并操作

我们将两个有序的数据集合合并成一个有序的数据集合的方法称为归并
链表的归并操作:
代码如下:

#include<stdio.h>
#include<malloc.h>
#include<string.h>
typedef struct  _STU//定义一个结构体
{
	int id;
	char name[32];
	int score;
	struct  _STU *next;
}STU, *PSTU;

void InsertHead(PSTU * ppHead, int id, char name[], int score)//头插法
{
	PSTU pNew = (PSTU)malloc(sizeof(STU));
	pNew->id = id;
	strcpy(pNew->name, name);
	pNew->score = score;
	pNew->next = *ppHead;
	*ppHead = pNew;
}
void InsertTail(PSTU * ppHead, int value, char name[], int score)//尾插法
{
	if (NULL == *ppHead)
	{
		InsertHead(ppHead, value, name, score);
	}
	else
	{
		PSTU pPos = *ppHead;
		while (pPos->next != NULL)
		{
			pPos = pPos->next;
		}

		PSTU pNew = (PSTU)malloc(sizeof(STU));
		pNew->id = value;
		strcpy(pNew->name, name);
		pNew->score = score;
		pNew->next = *ppHead;
		pNew->next = NULL;
		pPos->next = pNew;
	}
}
void Show(const PSTU pHead)//输出函数
{
	PSTU pos = pHead;
	while (pos != NULL)
	{
		printf("%d:%s:%d\n", pos->id, pos->name, pos->score);
		pos = pos->next;
	}

}
void Sequence(PSTU *pphead, PSTU *pphead1, PSTU *pphead2)//归并排序函数
{
	PSTU pos = NULL, pos1 = NULL, pos2 = NULL,pos3=NULL;
	PSTU t = NULL;
	pos = *pphead;//定义三个指针,分别指向三个链表的头结点
	pos1 = *pphead1;//定义三个指针,分别指向三个链表的头结点
	pos2 = *pphead2;//定义三个指针,分别指向三个链表的头结点
	while (pos1 != NULL&&pos2 != NULL)//第一个与第二个链表都不为空时
	{
		if (pos1->id < pos2->id)//如果第一个链表的ID小于第二个链表的ID,就将它插入到第三个链表中
		{
			InsertTail(pphead,pos1->id , pos1->name, pos1->score);
			t = pos1;
			pos1 = pos1->next;
			free(t);
			t = NULL;
		}
		else
		{
			InsertTail(pphead, pos2->id, pos2->name, pos2->score);
			t = pos2;
			pos2 = pos2->next;
			free(t);
			t = NULL;
		}
		
	}
	if (pos1 != NULL)//最终会有一个链表遍历完,另一个链表没有遍历完,将没遍历完的链表剩下的节点全部接到第三个链表后面
	{
		while (pos1 != NULL)
		{
			InsertTail(pphead, pos1->id, pos1->name, pos1->score);
			t = pos1;
			pos1 = pos1->next;	
			free(t);
			t = NULL;
		}
	}
	else
	{
		while (pos2 != NULL)
		{
			InsertTail(pphead, pos2->id, pos2->name, pos2->score);
			t = pos2;
			pos2 = pos2->next;
			free(t);
			t = NULL;

		}
	}
	
}
int main()
{
	PSTU head = NULL;
	PSTU head1=NULL;
	PSTU head2=NULL;
	InsertTail(&head1, 1, "南宫问天", 59);
	InsertTail(&head1, 3, "南宫毅", 66);
	InsertTail(&head1, 5, "石昊", 68);
	InsertTail(&head1, 12, "叶凡", 98);
	InsertTail(&head1, 14, "王腾", 79);
	Show(head1);

	InsertTail(&head2, 2, "那撸多", 58);
	InsertTail(&head2, 6, "哈斯给", 63);
	InsertTail(&head2, 10, "楚风", 60);
	InsertTail(&head2, 15, "华云飞", 82);
	InsertTail(&head2, 16, "姜太虚", 100);
	puts("-----------------------------");
	Show(head2);

	Sequence(&head,&head1,&head2);
	puts("------------------------------");
	Show(head);
	return 0;
}

结果如下所示:
在这里插入图片描述
流程示意图:
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值