首页 > 代码库 > (数据结构)部分稀疏矩阵的操作
(数据结构)部分稀疏矩阵的操作
//顺序
typedef struct {
int row,
col; //非零元素的行号、列号
ElemType val; //元素值
}
Triple;
typedef struct {
int m,
n,
t; //矩阵的行、列数及非零元素个数
Triple sm[MaxTerms + 1]; //三元组线性表,从sm[1]开始
}
SMatrix;
void InitMatrix(SMatrix & M) {
M.m = 0;
M.n = 0;
M.t = 0;
}
void InputMatrix(SMatrix & M, int m, int n) { //以行序为主序次序每行输入一个三元组,最后以 “0 0 0” 结束
int row,
col,
val,
k = 0;
cin >> row >> col >> val;
while (row != 0) {
k++;
M.sm[k].row = row;
M.sm[k].col = col;
M.sm[k].val = val;
cin >> row >> col >> val;
}
M.m = m;
M.n = n;
M.t = k;
}
//链式
typedef struct Node {
int row,
col; //非零元素的行号、列号
ElemType val; //元素值
struct Node * next;
}
TripleNode;
typedef struct {
int m,
n,
t; //矩阵的行、列数及非零元素个数
TripleNode * vector[MaxRows + 1]; //从vector[1]开始
}
LMatrix;
void InitMatrix(LMatrix & M) {
M.m = 0;
M.n = 0;
M.t = 0;
for (int i = 1; i <= MaxRows; i++) M.vector[i] = NULL;
}
void InputMatrix(LMatrix & M, int m, int n) { //以行序为主序次序每行输入一个三元组,最后以 “0 0 0” 结束
TripleNode * p,
*q;
int row,
col,
val,
k = 0;
cin >> row >> col >> val;
while (row != 0) {
k++;
p = new TripleNode;
p - >row = row;
p - >col = col;
p - >val = val;
p - >next = NULL;
//插在单链表末尾
q = M.vector[row];
if (q == NULL) M.vector[row] = p;
else {
while (q - >next != NULL) q = q - >next;
q - >next = p;
}
cin >> row >> col >> val;
}
M.m = m;
M.n = n;
M.t = k;
}
/*--------------------*/
SMatrix Transpose(SMatrix M) //转置
{
int k = 1;
SMatrix S;
InitMatrix(S);
S.m = M.n;
S.n = M.m;
S.t = M.t;
if (S.t == 0) return S;
for (int col = 1; col <= M.n; col++) for (int i = 1; i <= M.t; i++) if (M.sm[i].col == col) {
S.sm[k].row = M.sm[i].col;
S.sm[k].col = M.sm[i].row;
S.sm[k].val = M.sm[i].val;
k++;
}
return S;
}
LMatrix Add(LMatrix M1, LMatrix M2) {
int k = 0; //统计非零元个数
Triple * p1,
*p2,
*p,
*newptr;
LMatrix M;
InitMatrix(M);
M.m = M1.m;
M.n = M1.n;
if ((M1.t == 0) && (M2.t == 0)) return M;
for (int i = 1; i <= M1.m; i++) {
p1 = M1.vector[i];
p2 = M2.vector[i];
p = NULL;
while ((p1 != NULL) && (p2 != NULL)) {
if (p1 - >col < p2 - >col) {
newptr = new TripleNode; * newptr = *p1;
p1 = p1 - >next;
} else if (p1 - >col > p2 - >col) {
newptr = new TripleNode; * newptr = *p2;
p2 = p2 - >next;
} else {
if (p1 - >val + p2 - >val == 0) {
p1 = p1 - >next;
p2 = p2 - >next;
continue;
} else {
newptr = new TripleNode; * newptr = *p1;
newptr - >val += p2 - >val;
p1 = p1 - >next;
p2 = p2 - >next;
}
}
//以下插入newptr到第i行链尾,并后移p指针
newptr - >next = NULL;
if (p == NULL) M.vector[i] = newptr;
else p - >next = newptr;
p = newptr;
k++;
} //while
while (p1 != NULL) {
newptr = new TripleNode; * newptr = *p1;
newptr - >next = NULL;
if (p == NULL) M.vector[i] = newptr;
else p - >next = newptr;
p = newptr;
p1 = p1 - >next;
k++;
} //while
while (p2 != NULL) {
newptr = new TripleNode; * newptr = *p2;
newptr - >next = NULL;
if (p == NULL) M.vector[i] = newptr;
else p - >next = newptr;
p = newptr;
p2 = p2 - >next;
k++;
} //while
} //for
M.t = k;
return M;
}
(数据结构)部分稀疏矩阵的操作