#include<iostream> #include<stdlib.h> using namespace std; const int maxn = 101; typedef struct OLNode { int i, j, e; struct OLNode *right, *down; }OLNode, *OLink; typedef struct { OLink *rhead, *chead; int mu, nu, tu; }CrossList; int m,n; int a[maxn][maxn]; int b[maxn][maxn];
CrossList CreateMatrix_OL(CrossList &M) { int t; int i, j, e; OLNode *p, *q; printf("输入矩阵的行数、列数和非0元素个数:"); scanf("%d%d%d", &m, &n, &t); M.mu = m; M.nu = n; M.tu = t; printf("请依次输入%d行三个一组(分别表示非零元的行,列,数值)的数据,最终以0 0 0结束\n",t); if (!(M.rhead = (OLink*)malloc((m + 1) * sizeof(OLink))) || !(M.chead = (OLink*)malloc((n + 1) * sizeof(OLink)))) { printf("矩阵初始化失败"); exit(0); } for (i = 1; i <= m; i++) { M.rhead[i] = NULL; } for (j = 1; j <= n; j++) { M.chead[j] = NULL; } for (scanf("%d%d%d", &i, &j, &e); 0 != i; scanf("%d%d%d", &i, &j, &e)) { if (!(p = (OLNode*)malloc(sizeof(OLNode)))) { printf("初始化三元组失败"); exit(0); } p->i = i; p->j = j; p->e = e; a[i][j] = e;
if (NULL == M.rhead[i] || 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 (NULL == M.chead[j] || 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 M; }
void display() { for (int i = 1; i <= m; i++) for (int j = 1; j <= n; j++) { cout << a[i][j] <<" "; if (j == n) cout << endl; } }
void TransposeSMatrix() { int col, row; for (col = 1; col <= n; col++) for (row = 1; row <= m; row++) b[col][row] = a[row][col];
}
void display_Transpose() { cout << "转置后的矩阵M:" << endl; for(int i = 1;i <= n;i++) for(int j = 1;j <= m;j++) { cout << b[i][j] << " "; if (j == m) cout << endl; }
} int main() { CrossList M; M.rhead = NULL; M.chead = NULL; M = CreateMatrix_OL(M); printf("输出矩阵M:\n"); display(); TransposeSMatrix(); display_Transpose(); return 0; }
|