按照课本上实现了稀疏矩阵的链式存储 [cce_cpp] #include<stdio.h> #include <malloc.h> struct MatNode { int row,col; struct MatNode *right,*down; union { int val; struct MatNode *next; }tag; }; struct MatNode *CreateMat() { int m,n,t,s,i,r,c,v; struct MatNode *h[100],*p,*q; printf("行数m,列数n,非零元素个数t:"); scanf("%d,%d,%d",&m,&n,&t); p=(struct MatNode *)malloc(sizeof(struct MatNode)); h[0]=p; p->row=m; p->col=n; s=m>n ? m:n; for(i=1;i<=s;i++) { p=(struct MatNode *)malloc(sizeof(struct MatNode)); h[i]=p; h[i-1]->tag.next=p; p->row=p->col=0; p->down=p->right=p; } h[s]->tag.next=h[0]; for(i=1;i<=t;i++) { printf("\t第%d个元素(行号m,列号n,值v):",i ); scanf("%d,%d,%d",&r,&c,&v); p=(struct MatNode *)malloc(sizeof(struct MatNode)); p->row=r; p->col=c; p->tag.val=v; q=h[r]; while(q->right!=h[r]&&q->right->col<c) q=q->right; p->right=q->right; q->right=p; q=h[c]; while(q->down!=h[c]&&q->down->row<r) q=q->down; p->down=q->down; } return (h[0]); } void prmat (struct MatNode *hm) { struct MatNode *p,*q; printf("\n 按行表输出矩阵元素:\n"); printf("row=%d col=%d\n",hm->row,hm->col);p=hm->tag.next; while(p!=hm) { q=p->right; while(p!=q) { printf("\t %d,%d,%d\n",q->row,q->col,q->tag.val); q=q->right; } p=p->tag.next; } } main() { struct MatNode *hm; hm=(MatNode *)malloc(sizeof(MatNode)); hm=CreateMat(); prmat(hm); } [/cce_cpp]
实现如下图
