// 通过列的顺序插入非零元素到转置矩阵中 if (numNonZero > 0) { for (int col = 0; col < cols; ++col) { for (int i = 1; i <= numNonZero; ++i) { if (tripletMatrix[i].col == col) { transposedMatrix.push_back({tripletMatrix[i].col, tripletMatrix[i].row, tripletMatrix[i].value}); } } } }
// 统计每一列中非零元素的个数 for (int i = 1; i <= numNonZero; ++i) { count[tripletMatrix[i].col]++; }
// 计算每一列在转置矩阵中的起始位置 for (int i = 1; i < cols; ++i) { index[i + 1] = index[i] + count[i - 1]; }
// 填充转置矩阵的三元组顺序表 for (int i = 1; i <= numNonZero; ++i) { int col = tripletMatrix[i].col; int pos = index[col]; transposedMatrix[pos] = {tripletMatrix[i].col, tripletMatrix[i].row, tripletMatrix[i].value}; index[col]++; } }
return transposedMatrix; }
十字链表
IMG_20241019_170755
定义
类中定义了两个链表数组,用于存储每一行和每一列的头节点指针
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
// 节点定义 structOLNode { int row; // 行号 int col; // 列号 int value; // 元素值 OLNode* right; // 指向右边的节点 OLNode* down; // 指向下面的节点
OLNode(int r, int c, int val) : row(r), col(c), value(val), right(nullptr), down(nullptr) {} };