📄 十字链表cross.cpp
字号:
#include <stdio.h>
#include <malloc.h>
#define M 3
#define N 3
#define Max ((M)>(N)?(M):(N))
typedef int ElemType;
typedef struct mtxn
{
int row;
int col;
struct mtxn *right,*down;
union
{
ElemType value;
struct mtxn *link;
} tag;
} MatNode;
void CreatMat(MatNode *&mh,ElemType a[][N])
{
int i,j;
MatNode *h[Max],*p,*q,*r;
mh=(MatNode *)malloc(sizeof(MatNode));
mh->row=M;mh->col=N;
r=mh;
for (i=0;i<Max;i++)
{
h[i]=(MatNode *)malloc(sizeof(MatNode));
h[i]->down=h[i]->right=h[i];
h[i]->row=h[i]->col=0;
r->tag.link=h[i];
r=h[i];
}
r->tag.link=mh;
for (i=0;i<M;i++)
{
for (j=0;j<N;j++)
{
if (a[i][j]!=0)
{
p=(MatNode *)malloc(sizeof(MatNode));
p->row=i+1;p->col=j+1;p->tag.value=a[i][j];
q=h[i];
while (q->right!=h[i] && q->right->col<j+1)
q=q->right;
p->right=q->right;q->right=p;
q=h[j];
while (q->down!=h[j] && q->down->row<i+1)
q=q->down;
p->down=q->down;q->down=p;
}
}
}
}
void DispMat(MatNode *mh)
{
MatNode *p,*q;
printf("行=%d 列=%d\n", mh->row,mh->col);
p=mh->tag.link;
while (p!=mh)
{
q=p->right;
while (p!=q)
{
printf("%d\t%d\t%d\n", q->row,q->col,q->tag.value);
q=q->right;
}
p=p->tag.link;
}
}
bool access(MatNode *mh,int i,int j,ElemType &e)
{
if(i<0 || i>=mh->row || j<0 || j>=mh->col)
return false;
MatNode *p,*hi;
int k=1;
hi=mh->tag.link;
while(k<i)
{hi=hi->tag.link ;
k++;
}
p=hi->right;
while(p!=hi && p->col<j)
p=p->right;
if(p->col==j)
e=p->tag.value ;
else
e=0;
return true;
}
void main()
{
ElemType a[M][N]={{1,0,3},{0,2,0},{0,0,5}},e;
ElemType b[M][N]={{-1,0,2},{0,-2,0},{1,0,-5}};
// ElemType c[][5]={{0,5,0,0,8},{1,0,3,0,0},{0,-2,0,0,0},{6,0,0,0,0},{0,4,-9,0,0}};
MatNode *mx,*my;
CreatMat(mx,a);
bool k=access(mx,2,2,e);
CreatMat(my,b);
printf("a的三元组:\n");DispMat(mx);
printf("b的三元组:\n");DispMat(my);
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -