题目要求
题目要求十字链表为存储结构
十字链表大致就是这个样子
注意CrossList里面的两个指针其实是二级指针
#include <stdio.h>
#include <stdlib.h>
typedef struct Triple
{
int m;
int n;
int val;
struct Triple *right;
struct Triple *down;
}Triple;
typedef struct CrossLine
{
Triple **rowhead;
Triple **colhead;
int m;
int n;
int len;
}CrossLine;
void CreateCorsslist(CrossLine *s,int num)
{
int i;
s->len=num;
Triple *p,*temp;
s->rowhead=(Triple **)malloc((s->m+1)*sizeof(Triple*));
s->colhead=(Triple **)malloc((s->n+1)*sizeof(Triple*));
for(i=1;i<=s->n;i++)
{
s->colhead[i]=NULL;
}
for(i=1;i<=s->m;i++)
{
s->rowhead[i]=NULL;
}
if(s->len!=0)
{
for(int i=1;i<=s->len;i++)
{
p=(Triple*)malloc(sizeof(Triple));
scanf("%d %d %d",&p->m,&p->n,&p->val);
//行链表
if(s->rowhead[p->m]==NULL)
{
s->rowhead[p->m]=p;
p->right=NULL;
}
else
{
temp=s->rowhead[p->m];
while (temp->right!=NULL)
{
/* code */
temp=temp->right;
}
temp->right=p;
p->right=NULL;
}
//列链表
if(s->colhead[p->n]==NULL)
{
s->colhead[p->n]=p;
p->down=NULL;
}
else
{
temp=s->colhead[p->n];
while (temp->down!=NULL)
{
/* code */
temp=temp->down;
}
temp->down=p;
p->down=NULL;
}
}
}
}
void AddCrossList(CrossLine *a,CrossLine *b)
{
int i;
Triple *p,*temp1,*temp2;
for(i=1;i<=a->m;i++)//一行一行处理
{
if(b->rowhead[i]==NULL)//b的这一行没有数据
{
continue;//继续
}
else//b的这一行有数据
{
if(a->rowhead[i]==NULL)//a这一行没有数据,则把b复制过来
{
a->rowhead[i]=b->rowhead[i];
}
else//a b都有数据
{
temp1=a->rowhead[i];//遍历a
temp2=b->rowhead[i];//遍历b
p=a->rowhead[i];//始终指向a
while(1)
{
if(temp2->n == temp1->n)//位置一样
{
temp1->val=temp1->val+temp2->val;
if(temp1->val==0)//相加为0 则去掉该节点
{
Triple *pp=a->rowhead[i];
while(pp->right!=temp1) pp=pp->right;
pp->right=temp1->right;
}
temp1=temp1->right;
temp2=temp2->right;
}
else
{
if(temp1->n < temp2->n)//a列小
{
temp1=temp1->right;
}
else
{
if(temp1->n > temp2->n)//a列大
{
while(p->right!=temp1)
{
p=p->right;
}
p->right=temp2;
p=p->right;
temp2=temp2->right;
p->right=temp1;
p=a->rowhead[i];//p回去
}
}
}
if(temp2==NULL) break;
if(temp1==NULL) {temp1->right=temp2;break;}
}
}
}
}
}
void PrintCrossline(CrossLine *s)
{
for(int i=1;i<=s->m;i++)
{
Triple *temp=s->rowhead[i];
while (temp!=NULL)
{
/* code */
printf("%d %d %d\n",temp->m,temp->n,temp->val);
temp=temp->right;
}
}
}
int main()
{
int m,n,t1,t2;
scanf("%d %d %d %d",&m,&n,&t1,&t2);
CrossLine a,b;
a.m=m;
b.m=m,
a.n=n;
b.n=n;
a.len=t1;
b.len=t2;
CreateCorsslist(&a,t1);
CreateCorsslist(&b,t2);
AddCrossList(&a,&b);
PrintCrossline(&a);
return 0;
}