线性链表的应用,即编程实现两个矩阵的条件链接。

img


#include<stdio.h>
#include<stdlib.h>
#define MaxCol 10
typedef int ElemType;
typedef struct Nodel
{ ElemType data[MaxCol];
struct Nodel *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;iRow;i++)
{ printf("第%d行:",i+1);
s=(DList *)malloc(sizeof(DList));
for(j=0;jCol;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;jCol;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=h1->Row;
h->Col=h1->Col+h2->Col;
h->next=NULL;
while(p!=NULL)
{ q=h2->next;
while(q!=NULL)
{ if(p->data[i-1]==q->data[j-1])
{ s=(DList *)malloc(sizeof(DList));
for(k=0;kCol;k++)
s->data[k]=p->data[k];
for(k=0;kCol;k++)
s->data[h1->Col+k]=q->data[k];
if(h->next==NULL)
h->next=s;
else
r->next=s;
r=s;

  }
  q=q->next;
  }
  p=p->next;
  }
  r->next=NULL;

}
int main()
{ HList *h1=NULL,*h2=NULL,*h=NULL;
printf("表1:\n");
CreateTable(h1);
printf("表2:\n");
CreateTable(h2);
LinkTable(h1,h2,h);

  printf("连接结果表:\n");
  DispTable(h);
  DestroyTable(h1);
  DestroyTable(h2);
  DestroyTable(h);
  return 1;

}