c++稀疏矩阵的十字链表
时间: 2023-12-25 08:28:24 浏览: 93
以下是C++中稀疏矩阵的十字链表实现:
```c++
#include<iostream>
using namespace std;
// 十字链表结构体
typedef struct OLNode{
int i, j; // 该非零元素的行列下标
int e; // 该非零元素的值
struct OLNode *right, *down; // 该非零元素所在行列链表的后继指针
}OLNode, *OLink;
typedef struct{
OLink *rhead, *chead; // 行列链表头指针数组
int m, n, k; // 稀疏矩阵的行数、列数、非零元素个数
}CrossList;
// 创建稀疏矩阵的十字链表
void CreateSMatrix_OL(CrossList &M){
int m, n, k;
cout << "请输入稀疏矩阵的行数、列数、非零元素个数:" << endl;
cin >> m >> n >> k;
M.m = m;
M.n = n;
M.k = k;
M.rhead = new OLink[m+1]; // 行链表头指针数组
M.chead = new OLink[n+1]; // 列链表头指针数组
for(int i=1; i<=m; i++){
M.rhead[i] = NULL;
}
for(int j=1; j<=n; j++){
M.chead[j] = NULL;
}
cout << "请按行序输入每个非零元素的行、列、值:" << endl;
for(int i=1; i<=k; i++){
int row, col, value;
cin >> row >> col >> value;
OLink p = new OLNode;
p->i = row;
p->j = col;
p->e = value;
// 插入到行链表中
if(M.rhead[row] == NULL || M.rhead[row]->j > col){
p->right = M.rhead[row];
M.rhead[row] = p;
}
else{
OLink pre = M.rhead[row];
while(pre->right && pre->right->j < col){
pre = pre->right;
}
p->right = pre->right;
pre->right = p;
}
// 插入到列链表中
if(M.chead[col] == NULL || M.chead[col]->i > row){
p->down = M.chead[col];
M.chead[col] = p;
}
else{
OLink pre = M.chead[col];
while(pre->down && pre->down->i < row){
pre = pre->down;
}
p->down = pre->down;
pre->down = p;
}
}
}
// 输出稀疏矩阵的十字链表
void PrintSMatrix_OL(CrossList M){
cout << "稀疏矩阵的十字链表为:" << endl;
for(int i=1; i<=M.m; i++){
OLink p = M.rhead[i];
for(int j=1; j<=M.n; j++){
if(p && p->j == j){
cout << p->e << " ";
p = p->right;
}
else{
cout << "0 ";
}
}
cout << endl;
}
}
int main(){
CrossList M;
CreateSMatrix_OL(M);
PrintSMatrix_OL(M);
return 0;
}
```
阅读全文
相关推荐













