当前位置:C++技术网 > 资讯 > 数据结构中单链表求集合数组的并集-算上集合数组重合的元素

数据结构中单链表求集合数组的并集-算上集合数组重合的元素

更新时间:2016-04-07 22:34:20浏览次数:1+次

我们在VS中新建一个实现文件,然后写上代码:

#include "windows.h"
#include "stdio.h"
#include "stdlib.h"
#include "algorithm"

#include "LinkList.h"

using namespace std;


void MergeList(LinkList A, LinkList B, LinkList *C)
{
	ListNode *pa, *pb, *pc;
	pa=A->next;
	pb=B->next;
	*C=A;
	(*C)->next=NULL;
	pc=*C;
	while(pa&& pb)
	{
		if(pa->data <= pb->data)
		{
			pc->next=pa;
			pc=pa;
			pa=pa->next;

		}
		else
		{
			pc->next=pb;
			pc=pb;
			pb=pb->next;
		}
	}
	pc->next=pa ? pa: pb;
	free(B);
}


int main()
{
	int i;
    DataType a[]={2,3,6,7,9,14,65,45,67};
	DataType b[]={3,4,7,11,34,56,45,67};
	
	std::sort(a,a+8);
	std::sort(b,b+7);

	
	LinkList A,B,C;
	ListNode *p;

	InitList(&A);
	InitList(&B);

	for(i=1; i<=sizeof(a)/sizeof(int); i++)
	{
		if(InsertList(A,i,a[i-1])==0)
		{
			printf("位置不合法!\n");
			return 0;
		}
	}

	for(i=1; i<=sizeof(b)/sizeof(int); i++)
	{
		if(InsertList(B,i,b[i-1])==0)
		{
			printf("位置不合法!\n");
			return 0;
		}
	}

	printf("单链表A中有%d个元素\n",ListLength(A));
	for(i=1; i<=ListLength(A); i++)
	{
		p=Get(A,i);
		if(p)
		{
			printf("%4d",p->data);
		}
	}
	printf("\n");

	printf("单链表B中有%d个元素\n",ListLength(B));
	for(i=1; i<=ListLength(B); i++)
	{
		p=Get(B,i);
		if(p)
		{
			printf("%4d",p->data);
		}
	}
	printf("\n");

	MergeList(A,B,&C);

	printf("将单链表A和B的元素合并之后到C中,C中的元素共有%d个:\n",ListLength(C));
	for(i=1; i<=ListLength(C); i++)
	{
		p=Get(C,i);
		if(p)
		{
			printf("%4d",p->data);
		}
	}
	printf("\n");

	system("pause");
}
实现: