十字链表的建立与输出
#include <stdio.h> #include <string.h> #include <stdlib.h> #include <malloc.h> #define ok 1 #define overflow 0 #define error -1 typedef int ElemType; typedef int Status; typedef struct OLNode { int i,j; ElemType e; struct OLNode *right,*down; }OLNode, *OLink; typedef struct{ OLink *rhead,*chead; int mu,nu,tu; }CrossList; Status CreateSMatrix_OL(CrossList &M) { int m,n,t; int i,j,e; int jud; OLink p,q; printf("请输入稀疏矩阵的行数、列数、非零元个数:"); scanf("%d%d%d", &m, &n, &t); M.mu=m; M.nu=n; M.tu=t; jud=t; if(!(M.rhead=(OLink *)malloc((m+1)*sizeof(OLink)))) exit(overflow); if(!(M.chead=(OLink *)malloc((n+1)*sizeof(OLink)))) exit(overflow); for(i=0;i<=m;i++) M.rhead[i]=NULL; for(i=0;i<=n;i++) M.chead[i]=NULL; for(jud=0; jud<t;jud++) { scanf("%d%d%d", &i, &j, &e); if(!(p=(OLNode *)malloc(sizeof(OLNode)))) exit(overflow); p->i=i; p->j=j; p->e=e; if(M.rhead[i]==NULL||M.rhead[i]->j>j) {p->right=M.rhead[i]; M.rhead[i]=p;} else{ for(q=M.rhead[i];(q->right)&&(q->right->j<j);q=q->right); p->right=q->right; q->right=p; } if(M.chead[j]==NULL||M.chead[j]->i>i) {p->down=M.chead[j]; M.chead[j]=p;} else{ for(q=M.chead[j];(q->down)&&q->down->i<i;q=q->down); p->down=q->down; q->down=p; } } return ok; } int PrintSMatrix(CrossList M) { int i,j; OLink p; printf("%d行%d列%d个非零元素\n",M.mu,M.nu,M.tu); printf("请输入选择(1.按行输出 2.按列输出): "); scanf("%d",&i); switch(i) { case 1: for(j=1;j<=M.mu;j++) { p=M.rhead[j]; while(p) { printf("%d行%d列值为%d\n",p->i,p->j,p->e); p=p->right; } } break; case 2: for(j=1;j<=M.nu;j++) { p=M.chead[j]; while(p) { printf("%d行%d列值为%d\n",p->i,p->j,p->e); p=p->down; } } } return ok; } int main() { CrossList M; CreateSMatrix_OL(M); PrintSMatrix(M); return 0; }