表的自然连接-c语言

#include
#include
#include
#define N 100
typedef int ElemType;
typedef int Status;
typedef struct LNode1{
	ElemType data[100];
	struct LNode1 *next;
}*DList,lnode1;

typedef struct LNode2{
	ElemType row,col;//行数,列数
	struct LNode1 *next;
}*HList,lnode2;

void CreatTable(HList &h){
	int i,j;
	DList s,r;
	h=(HList)malloc(sizeof(lnode2));
	h->next=NULL;
	printf("请输入表的行数和列数:\n");
	scanf("%d%d",&h->row,&h->col);
	for(i=0;i<h->row;i++){
		printf("请输入第%d行的数据:\n",i+1);
		s=(DList)malloc(sizeof(lnode1));
		for(j=0;j<h->col;j++){
			scanf("%d",&s->data[j]);
		}
		if(h->next==NULL){
			h->next=s;
		}
		else{
			r->next=s;
		}
		r=s;
	}
	r->next=NULL;
}
void LinkTable(HList &h1,HList &h2,HList &h){
	int i,j;
	int m,n;
	DList p1,p2,s,r;
	p1=h1->next;
	p2=h2->next;
	h=(HList)malloc(sizeof(lnode2));
	h->row=0;
	h->col=h1->col+h2->col;
	h->next=NULL;
	printf("请输入连接两个表的列序号\n");
	scanf("%d %d",&m,&n);
	while(p1!=NULL){
		while(p2!=NULL){
			if(p1->data[m-1] == p2->data[n-1]){
				s=(DList)malloc(sizeof(lnode1));
				for(i=0;i<h1->col;i++){
					s->data[i]=p1->data[i];
				}
				for(i=0,j=h1->col;i<h2->col;i++,j++){
					s->data[j]=p2->data[i];
				}
				if(h->next==NULL){
					h->next=s;
				}
				else{
					r->next=s;
				}
				r=s;
				h->row++;
			}
			p2=p2->next;
		}
		p1=p1->next;
		p2=h2->next;
	}
	r->next=NULL;
}
void printList(HList h){
	int i;
	DList p=h->next;
	printf("连接后的矩阵行数,列数为%d %d\n",h->row,h->col);
	while(p!=NULL){
		for(i=0;i<h->col;i++){
			printf("%d ",p->data[i]);
		}
		printf("\n");
		p=p->next;
	}
}
void DestroyTable(HList &h){
	DList pre=h->next,p=pre->next;
	while(p!=NULL){
		free(pre);
		pre=p;
		p=p->next;
	}
	free(pre);
	free(h);
}
int main(){
	HList h1,h2,h;

	printf("表1:\n");
	CreatTable(h1);
	printf("表2:\n");
	CreatTable(h2);

	LinkTable(h1,h2,h);
	printf("连接结果表:\n");
	printList(h);

	DestroyTable(h1);
	DestroyTable(h2);
	DestroyTable(h);
	return 0;
}

你可能感兴趣的:(表的自然连接-c语言)