單鏈表實現集合求並集

用不帶頭結點的單鏈表實現集合求兩個集合的並集。要求不破壞原來的集合。

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:主要就是鏈表的複製操作和添加第二個集合的時候去除重複元素。當然,集合的基本數學概念還是需要懂的。


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章