数据结构-链表的合并

#include <iostream>
using namespace std;

typedef struct node 
{
    
    
	int data;
	struct node *next;
} node, *list;

void chuangjian(list &l) 
{
    
     //创建链表
	l = new node;
	l->next = NULL;
}

void shuru(list &l, int n) 
{
    
     //链表数据的输入
	int i;
	node *p, *r;
	cout << "请输入" << n << "个数";
	r = l;
	for (int i = 0; i < n; i++) 
	{
    
    
		p = new node;
		cin >> p->data;
		p->next = NULL;
		r->next = p;
		r = p;
	}
}

void charu(list &l, int e) 
{
    
    
	node *p;
	p = new node;
	p->data = e;
	p->next = l->next;
	l->next = p;
}

bool panduan(list &l, int e) 
{
    
     //判断有没有e这个元素
	node *p;
	p = l->next;
	while (p != NULL) 
	{
    
    
		if (p->data == e) 
		{
    
    
			return true;
		}
		p = p->next;
	}
	return false;
}

void hebing(list &la, list lb) 
{
    
     //不同的才合并
	int e;
	node *p;
	p = lb->next;
	while (p != NULL) 
	{
    
    
		e = p->data;
		if (!panduan(la, e)) 
		{
    
    
			charu(la, e);
		}
		p = p->next;
	}
}

void shuchu(list l) 
{
    
    
	node *p;
	p = l->next;
	while (p != NULL) 
	{
    
    
		cout << p->data << " ";
		p = p->next;
	}
	cout << endl;
}

int main () 
{
    
    
	list la, lb;
	int n, m;
	chuangjian(la);
	chuangjian(lb);
	cout << "请输入线性表la的元素的个数" << endl;
	cin >> n;
	shuru(la, n);
	cout << "请输入线性表lb的元素的个数" << endl;
	cin >> m;
	shuru(lb, m);
	cout << "la与lb合并之后" << endl;
	hebing(la, lb);
	shuchu(la);
	return 0;
}

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_52045928/article/details/121645586