|

楼主 |
发表于 2016-4-22 23:41:02
|
显示全部楼层
本帖最后由 W-LQ 于 2016-5-7 12:19 编辑
这是整个的了
目的: 为的是完成两个表h1和h2的自然连接
算法思路是先要输入两个表的连接序号i和j,然后扫描单链表h1。对与h1的每个节点,从头至尾扫描单链表h2,若自然连接条件成立,即h1的当前节点*p和h2的当前节点*q满足:p->data[i-1]==q->data[j-1],则在新建单链表h中添加一个新节点。新建的单链表h采用尾插法建表放式创建的。
#include <stdio.h>
#include <malloc.h>
#define MaxCol 10
typedef int ElemType;
typedef struct Node1
{
ElemType data[MaxCol];
struct Node1 *next;
}DList;
typedef struct Node2
{
int Row,Col;
DList *next;
}HList;
void CreateTable(HList *&h)
{
int i,j;
DList *r, *s;
h=(HList *)malloc(sizeof(HList));
printf("表的行数,列数:");
scanf("%d%d",&h->Row,&h->Col);
for (i=0;i<h->Row;i++)
{ printf("第%d行:",i+1);
s=(DList *)malloc(sizeof(DList));
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 DestroyTable(HList *&h)
{
DList *pre=h->next, *p=pre->next;
while(p!=NULL)
{
free(pre);
pre=p;
p=p->next;
}
free(pre);
free(h);
}
void DispTable(HList *h)
{
int j;
DList *p=h->next;
while(p!=NULL)
{
for(j=0;j<h->Col;j++)
printf("%4d",p->data[j]);
printf("\n");
p=p->next;
}
}
void LinkTable(HList *h1,HList *h2,HList *&h)
{
int i,j,k;
DList *p=h1->next,*q,*s,*r;
printf("连接字段是:第1个表序号,第2个表序号:");
scanf("%d%d",&i,&j);
h=(HList *)malloc(sizeof(HList));
h->Row=0;
h->Col=h1->Col+h2->Col;
h->next=NULL;
while(p!=NULL)
{
q=h2->next;
while(p!=NULL)
{
if(p->data[i-1]==q->data[j-1])
{
s=(DList *)malloc(sizeof(DList));
for(k=0;k<h1->Col;k++)
s->data[k]=p->data[k];
for(k=0;k<h2->Col;k++)
s->data[h1->Col+k]=q->data[k];
if(h->next==NULL)
h->next=s;
else
r->next=s;
r=s;
h->Row++;
}
q=q->next;
}
p=p->next;
}
r->next=NULL;
}
//这是主程序
#include"p.cpp"
void main()
{
HList *h1,*h2,*h;
printf("表1:\n");
CreateTable(h1);
printf("表1:\n");
CreateTable(h2);
LinkTable(h1,h2,h);
printf("连接表结果:\n");
DestroyTable(h1);
DestroyTable(h2);
DestroyTable(h);
} |
|