概述
#include<iostream>
#include<ctime>
using namespace std;
struct Node;
typedef struct Node* PtrToNode;
typedef PtrToNode Position;
typedef PtrToNode List;
struct Node {
int data;
struct Node* next;
struct Node* pre;
};
//创建链表
List createList()
{
PtrToNode L = (PtrToNode)malloc(sizeof(struct Node));
if (L == NULL)
{
cout << "分配内存空间失败!" << endl;
}
else
{
L->next = NULL;
}
return L;
}
//将数据插入到链表当中
void Insert(List& L, int e)
{
PtrToNode tmpcell = (PtrToNode)malloc(sizeof(struct Node));
if (tmpcell == NULL)
{
cout << "分配内存空间失败!" << endl;
}
else
{
//尾插法实现数据输入
tmpcell->data = e;
tmpcell->next = L->next;
L->next = tmpcell;
}
}
//找出两个链表中相同的元素,并在L1中删掉相同的元素
void B(List& L1, List& L2)
{
Position p = L1->next;
Position q = L2->next;
while (q)
{
while (p)
{
if (p->data == q->data)
{
Position tmp;//用于存储要删掉的节点的位置
tmp = p;
L1->next = p->next;
free(tmp);
}
p = p->next;
}
q = q->next;
}
}
//将并集输出
void printDouList(List& L1, List& L2)
{
Position p = L1->next;
Position q = L2->next;
while (p)
{
cout << p->data << " ";
//p = p->next;
p = p->next;
}
while (q)
{
cout << q->data << " ";
//q = q->next;
q = q->next;
}
}
//单个集合(链表)输出
void print(List& L)
{
Position p = L->next;
while (p)
{
cout << p->data << " ";
p = p->next;
}
}
int main()
{
//创建两条链表
List L1 = createList();
List L2 = createList();
srand(time(0));
cout << "测试" << endl;
//生成随机数插入到链表当中
for (int i = 0; i < 10; i++)
{
int tmp1 = rand() % 100;
Insert(L1, tmp1);
int tmp2 = rand() % 100;
Insert(L2, tmp2);
}
cout << "L1" << endl;
print(L1);
cout << endl;
cout << "L2" << endl;
print(L2);
cout << endl;
B(L1, L2);
printDouList(L1, L2);
return 0;
}
最后
以上就是香蕉汉堡为你收集整理的用单链表实现两个集合的并集的全部内容,希望文章能够帮你解决用单链表实现两个集合的并集所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复