@【数据结构】(链表合并)

@【数据结构】(链表合并)

建立带头结点的链表,两个链表大小与元素值由键盘输入,得到合成链表,得到排序后的合成链表

#include<stdio.h>
#include<iostream>
using namespace std;
typedef struct list
{
	int data;
	struct list *next;
}*LIST, LNode;
void InitList(LIST *L)	/* 初始化链表 */
{
	*L = (LNode *)malloc(sizeof(LNode));   //带头结点的链表初始化
	(*L)->next = NULL;
}
void OutputList(LIST L)
{
	LNode *p;
	p = L->next;
	while (p)
	{
		cout << p->data << "  ";
		p = p->next;
	}
}
//在带头结点的单链表的表尾插入元素,建立一个单链表
LIST CreateList(LIST L,int a)
{
	LNode *R;
	int x;
	R = L;
	cout << "请输入线性表中的元素" << endl;
	for(int i=0;i<a;i++)
	{
		cin >> x;
		R->next = (LNode *)malloc(sizeof(LNode));
		R->next->data = x;
		R = R->next;
	}
	R->next = NULL;
	return L;
}
void order(LIST L)
{
	LNode *pre,*q, *l1, *l2;
	l1 = L->next;  
	q = l1->next;   
	l1->next = NULL;  //将原来的链L断开
	while (q) 
	{
		l2 = q; 
		q = q->next; 
		pre = L;     //pre是待插入位置的前驱
		l1 = L->next; //l1是待插入位置的后继
		while (l1 != NULL && l1->data < l2->data) //寻找合适的插入点
		{
			pre = l1;
			l1 = l1->next;
		}
		//插入合适位置
		l2->next = l1;
		pre->next = l2;
	}
	
	cout << "排序后为:";
	OutputList(L);
}
void merge(LIST L1, LIST L2)     //合并两个表,L1元素在前,L2元素在后
{

	LNode *p, *q;
	p = L1->next; q = L2->next;
	while (p->next != NULL)
	{
		p = p->next;
	}
	p->next = q;
	free(L2);
	cout << "合并后链表为:";
	OutputList(L1);
	cout << endl;
	order(L1);
	cout << endl;
}

void main()
{
	int m, n; LIST A, B;
	InitList(&A), InitList(&B);
	cout << "请输入线性表A的长度:";
	cin >> m;
	CreateList(A, m);
	cout << "请输入线性表B的长度:";
	cin >> n;
	CreateList(B, n);
	if (m >= n)
		merge(A, B);   //合并并排序
	else 
		merge(B, A);
	system("pause");	
}

测试示例:
在这里插入图片描述

发布了20 篇原创文章 · 获赞 1 · 访问量 78

猜你喜欢

转载自blog.csdn.net/gsgs1234/article/details/104844452