您的位置:首页 > 理论基础 > 数据结构算法

单链表实现集合求并集

2016-04-12 00:37 483 查看
用不带头结点的单链表实现集合求两个集合的并集。要求不破坏原来的集合。

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:主要就是链表的复制操作和添加第二个集合的时候去除重复元素。当然,集合的基本数学概念还是需要懂的。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  数据结构 算法