C语言两个线性表的自然连接

//表的自然连接,表a的第i列和表b的第j列相等
#include <stdio.h>
#include <stdlib.h>
#define MaxCol 10 //最大列数
typedef struct Node
{
	int data[MaxCol];//一行的数据
	Node* next;
}Row;
typedef struct
{
	int row, col;//行数列数
	Row* next;//指向第一行
}Table;//头结点类型
void CreatTable(Table*& t) {
	int i, j;
	//尾结点r
	Row* r, * s;
	t = (Table*)malloc(sizeof(Table));
	t->next = NULL;
	r = (Row*)malloc(sizeof(Row));
	printf("请输入行数和列数:");
	scanf_s("%d%d", &t->row, &t->col);
	for (i = 0; i < t->row; i++) {
		printf("第%d行:", i + 1);
		s = (Row*)malloc(sizeof(Row));
		for (j = 0; j < t->col; j++) {
			scanf_s("%d", &s->data[j]);
		}
		if (t->next == NULL) {
			t->next = s;
		}
		else {
			r->next = s;
		}
		r = s;
	}
	r->next = NULL;
}
void DestroyTable(Table*& t) {
	Row* pre = t->next, * p = pre->next;
	while (p != NULL) {
		free(pre);
		pre = p;
		p = p->next;
	}
	free(pre);
	free(t);
}
void DispTable(Table* t) {
	int j;
	Row* p = t->next;
	while (p != NULL) {
		for (j = 0; j < t->col; j++) {
			printf("%4d", p->data[j]);
		}
		printf("\n");
		p = p->next;
	}
}
void LinkTable(Table *t1, Table *t2, Table *&t) {
	int i, j, k;
	Row* p = t1->next, * q, * s, * r;
	printf("连接的字段是:第1个表序号,第2个表序号:");
	scanf_s("%d%d", &i, &j);
	t = (Table*)malloc(sizeof(Table));
	t->next = NULL;
	r = (Row*)malloc(sizeof(Row));
	t->row = 0;
	t->col = t1->col + t2->col;
	t->next = NULL;
	while (p != NULL) {
		q = t2->next;
		while (q != NULL) {
			if (p->data[i - 1] == q->data[j - 1]) {
				s = (Row*)malloc(sizeof(Row));
				for (k = 0; k < t1->col; k++) {
					s->data[k] = p->data[k];
				}
				for (k = 0; k < t2->col; k++) {
					s->data[t1->col + k] = q->data[k];
				}
				if (t->next == NULL) {
					t->next = s;
				}
				else {
					r->next = s;
				}
				r = s;
				t->row++;
			}
			q = q->next;
		}
		p = p->next;
	}
	r->next = NULL;
}
int main() {
	Table* t1, * t2, * t;
	printf("表1:\n");
	CreatTable(t1);
	printf("表2:\n");
	CreatTable(t2);
	LinkTable(t1, t2, t);
	printf("连接的结果表:\n");
	DispTable(t);
	DestroyTable(t1);
	DestroyTable(t2);
	DestroyTable(t);
	return 1;
}
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值