c語言版數據結構(奇蹟冬瓜)-鏈表實戰(1)A=AUB

//c語言版數據結構(奇蹟冬瓜)-鏈表實戰(1)A=AUB

//題目:假設利用兩個線性表LA和LB分別表示兩個集合A和B,現要求一個新的集合A=A∪B

//思想:
/*
主函數:
初始化集合A和集合B
給A和B集合輸入元素
當集合B中的元素不到最後一個元素時
{
   取出B中的元素
   和A中的元素比較
   if(A沒有B有)
   {
      插入A的集合裏面
   }
}
輸出合併後的集合
*/

/*
void main()
{
     List *A=InitL();
	 List *B=InitL();
	 Data d;
	 InputData(A,5);
	 InputData(B,4);
	 while(NULL!=B->next)
	 {
	      d=GetData(B);
		  if(Compare(A,d))
		  {
		     Insert(A,d);
		  }
		  B=B->next;
	 }
	 Output(A);
}

*/

//-----------頭文件---------------
  #include<stdio.h>
  #include<stdlib.h>

//-----------宏定義---------------

#define TRUE 1
#define ERROR 0
#define OVERFLOW -2

//-----------結構體和替換---------

typedef int Data;
typedef struct Node
{
	Data d;
	struct Node *next;
}List,*NList;

//-----------函數----------------

int InitL(NList L);
int InputData(NList L,int n);
Data GetData(NList L);
int Compare(NList L,Data d);
void Insert(NList L,Data d);
void OutPut(NList L);

//----------主函數--------------

void main()
{
	List La,Lb,*A=&La,*B=&Lb;
	int n;
	Data d;
	InitL(A);InitL(B);
	printf("輸入集合A的元素個數:");
	scanf("%d",&n);
	InputData(A,n);
	printf("輸入集合B的元素個數:");
	scanf("%d",&n);
	InputData(B,n);
	B=B->next;
	while(B)
	{
		d=GetData(B);
		printf("---%d---\n",d);
		if(Compare(A,d))
		{
			Insert(A,d);
		}
		B=B->next;
	}
	OutPut(A);
}

//----------其餘函數--------------

int InitL(NList L)
{
	if(!(L=(NList)malloc(sizeof(List))))
	{
		exit(OVERFLOW);
	}
	L->next=NULL;
	return TRUE;
}

int InputData(NList L,int n)
{
	NList TempNode=L,StartNode=L,NewNode;
	printf("輸入元素:");
	for(;n>0;n--)
	{
		if(!(NewNode=(NList)malloc(sizeof(List))))
	   {
		   exit(OVERFLOW);
		}
		scanf("%d",&NewNode->d);
		TempNode->next=NewNode;
		NewNode->next=NULL;
		TempNode=NewNode;
	}
	L=StartNode;
	return TRUE;
}

Data GetData(NList L)
{
	return L->d;
}

int Compare(NList L,Data d)
{
	NList TempL=L->next,StartL=L;
	while(TempL->next)
	{
		if(d==TempL->d)
		{
			return ERROR;
		}
		TempL=TempL->next;
	}
	L=StartL;
	return TRUE;
}

void Insert(NList L,Data d)
{
	NList TempL=L->next,StartL=L,NewNode;
	while(TempL->next)
	{
		TempL=TempL->next;
	}
	if(!(NewNode=(NList)malloc(sizeof(List))))
	{
		exit(OVERFLOW);
	}
	NewNode->d=d;
	TempL->next=NewNode;
	NewNode->next=NULL;
	L=StartL;
}

void OutPut(NList L)
{
	NList TempL=L->next,StartL=L;
	printf("A=AUB=");
	while(TempL)
	{
		printf("%d ",TempL->d);
		TempL=TempL->next;
	}
	L=StartL;
	getchar();
	getchar();
}


 

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