//表的自然连接,表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;
}
C语言两个线性表的自然连接
最新推荐文章于 2023-12-06 23:47:30 发布