Written by Robert_Wang in Southwest University of Science And Technology.
#include<iostream>
#define MaxCol 10
using namespace std;
typedef int ElemType;
typedef struct DNode
{
ElemType data[MaxCol];
struct DNode *next;
}DList;
typedef struct
{
int Col;
int Row;
DList * next;
}HList;
void CreateTable(HList *&h)
{
int i, j;
DList *r, *s;
h = new HList;
h->next = NULL;
cout << "输入表的行数,列数:" << endl;
cin >> h->Row >> h->Col;
for (i = 0; i < h->Row; i++)
{
cout << "第 " << i + 1 << " 行: ";
r = new DList;
for (j = 0; j < h->Col; j++)
{
cin >> r->data[j];
}
if (h->next == NULL) h->next = r;
else s->next = r;
s = r;
}
s->next = NULL;
}
void DestroyTable(HList *&h)
{
DList * pre = h->next, *p = pre->next;
while (p)
{
delete pre;
pre = p;
p = p->next;
}
delete pre;
delete h;
}
void DispTable(HList*h)
{
int i, j;
DList * p = h->next;
for (i = 0; i < h->Row; i++)
{
for (j = 0; j < h->Col; j++)
{
cout << p->data[j] << " ";
}
cout << endl;
p = p->next;
}
}
void LinkTable(HList *h1, HList *h2, HList *&h)
{
int i, j, k;
h = new HList;
h->next = NULL;
h->Col = h1->Col + h2->Col;
h->Row = 0;
cout << "连接字段:第一个表的序号,第二个表的序号: ";
cin >> i >> j;
DList *p = h1->next;
DList *s, *r;
while(p!=NULL)
{
DList *q = h2->next;
while(q!=NULL)
{
if (p->data[i - 1] == q->data[j-1])
{
s = new DList;
for (k = 0; k < h1->Col; k++) { s->data[k] = p->data[k]; }//将p复制到s
for (k = 0; k < h2->Col; k++) { s->data[k+h1->Col] = q->data[k]; }//将q复制到s
if (h->next == NULL) h->next = s;
else r->next = s;
r = s;
h->Row++;
}
q = q->next;
}
p = p->next;
}
r->next = NULL;
}
int main()
{
HList *h1,*h2,*h;
cout << "表1" << endl;
CreateTable(h1);
cout << "表2" << endl;
CreateTable(h2);
LinkTable(h1, h2, h);
cout<<"连接结果为:"<<endl;
DispTable(h);
DestroyTable(h);
DestroyTable(h1);
DestroyTable(h2);
return 0;
}