单链表实现集合求并集

用不带头结点的单链表实现集合求两个集合的并集。要求不破坏原来的集合。

typedef int ElemType;
typedef struct LNode
{
	ElemType data;
	struct LNode *next;
}LinkList;

void unionSet(LinkList *LA, LinkList *LB, LinkList *&LC)
{
	if (!LA && !LB)//a和b都空
	{
		LC = 0;
	}
	else if(LA && !LB)//a不空b空
	{
		LinkList *tc;
		LinkList *ta;

		LC = new LinkList();
		tc = LC;
		ta = LA;

		while (ta)
		{
			tc->data = ta->data;
			if (ta->next)
			{
				tc->next = new LinkList();
				tc = tc->next;
			}
			else
			{
				tc->next = 0;
			}
			ta = ta->next;
		}
	}
	else if (!LA && LB)//a空b不空
	{
		LinkList *tc;
		LinkList *tb;

		LC = new LinkList();
		tc = LC;
		tb = LB;

		while (tb)
		{
			tc->data = tb->data;
			if (tb->next)
			{
				tc->next = new LinkList();
				tc = tc->next;
			}
			else
			{
				tc->next = 0;
			}
			tb = tb->next;
		}
	}
	else if (LA && LB)
	{
		LinkList *tc, *rc;
		LinkList *ta;
		LinkList *tb;

		LC = new LinkList();
		tc = LC;
		ta = LA;

		while (ta)
		{
			tc->data = ta->data;
			if (ta->next)
			{
				tc->next = new LinkList();
				tc = tc->next;
			}
			else
			{
				rc = tc;
			}
			ta = ta->next;
		}

		tb = LB;

		while (tb)
		{
			ta = LC;

			while (ta != rc)
			{
				if (ta->data == tb->data)
				{
					break;
				}
				else
				{
					ta = ta->next;
				}
			}

			if (ta == rc) //之前没有找到
			{
				if (rc->data != tb->data)//最后一个元素也不是
				{
					tc->next = new LinkList();
					tc = tc->next;
					tc->data = tb->data;
				}
			}

			tb = tb->next;
		}

		tc->next = 0;
	}
}

void createLinkList(LinkList *&LA, ElemType data[], int n)
{
	LinkList *ta;
	for (int idx= 0; idx < n; idx++)
	{
		if (idx <= 0)
		{
			LA = new LinkList();
			LA->data = data[idx];
			LA->next = 0;
			ta = LA;
		}
		else
		{
			ta->next = new LinkList();
			ta=ta->next;
			ta->data = data[idx];
			ta->next=0;
		}
	}
}

int _tmain(int argc, _TCHAR* argv[])
{
	LinkList *LA, *LB, *LC;

	ElemType dataA[] = {5,4,6,1,8,3};
	ElemType dataB[] = {8,5,9,12,4,7,6,3};

	createLinkList(LA, dataA, 6);
	createLinkList(LB, dataB, 8);

	unionSet(LA, LB, LC);

	LinkList *tc = LC;
	while (tc)
	{
		printf("%4d", tc->data);
		tc = tc -> next;
	}

	printf("\n\n");

	tc = LA;
	while (tc)
	{
		printf("%4d", tc->data);
		tc = tc -> next;
	}

	printf("\n\n");

	tc = LB;
	while (tc)
	{
		printf("%4d", tc->data);
		tc = tc -> next;
	}

	return 0;
}


运行结果图



ps:主要就是链表的复制操作和添加第二个集合的时候去除重复元素。当然,集合的基本数学概念还是需要懂的。


  • 4
    点赞
  • 27
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

当当小螳螂

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值