//-----------------稀疏矩阵的十字链表存储-------------------
#include <iostream>
#include <cassert>
using namespace std;
typedef int ElemType;
typedef struct CLNode
{
int row;
int col;
ElemType e;
struct CLNode* right;//指向同一行中的下一个非零元
struct CLNode* down;//指向同一列的下一个非零元
}CLNode;
typedef struct
{
CLNode* rhead; //行和列链表头指针向量基址由CreateCSMatrix分配
CLNode* chead;
int rows; //行数
int cols; //列数
int nzs; //非零元个数
}CrossList;
//重置M矩阵为空状态
void ResetCSMatrix( CrossList &M )
{
if ( M.rhead != NULL )
{
delete M.rhead;
M.rhead = NULL;
}
if ( M.chead != NULL )
{
delete M.chead;
M.chead = NULL;
}
M.rows = 0;
M.cols = 0;
M.nzs = 0;
}
//创建十字链表稀疏矩阵
void CreateCSMatrix( CrossList &M )
{
cout << "输入矩阵的行数与列数:";
int r,c;
cin >> r >> c;
assert( r > 0 && c >0 );
if ( r <= 0 || c <=0 )
{
ResetCSMatrix( M );
return;
}
M.rows = r;
M.cols = c;
M.nzs = 0;
M.rhead = new CLNode[M.rows];
M.chead = new CLNode[M.cols];
assert( M.rhead != NULL && M.chead != NULL );
if ( M.rhead == NULL || M.chead == NULL )
{
ResetCSMatrix( M );
return;
}
for ( int i = 0; i < M.rows; ++i )
{
M.rhead[i].right = NULL;
M.rhead[i].down = NULL;
}
for ( int i = 0; i < M.cols; ++i )
{
M.chead[i].right = NULL;
M.chead[i].down = NULL;
}
cout << "请输入一个" << M.rows << "行"
<< M.cols << "列的矩阵M:" << endl;
int val;
for ( int i = 0; i < M.rows; ++i )
{
for ( int j = 0; j < M.cols; ++j )
{
cin >> val;
if ( val != 0 )
{
CLNode* p = new CLNode;
assert( p != NULL );
if ( !p )
{
ResetCSMatrix( M );
return;
}
p->row = i;
p->col = j;
p->e = val;
p->right = NULL;
p->down = NULL;
//将该结点插入至正确的位置上
//因为是从按行列输入的,按行序优先存储
//所以每次的插入位置都在最后一位
//先处理列之间的链接
CLNode* pInsertPos = &(M.chead[j]);
CLNode* pNext = pInsertPos->down;
while( pNext )
{
pInsertPos = pNext;
pNext = pNext->down;
}
pInsertPos->down = p;
//再处理行之间的链接关系
pInsertPos = &(M.rhead[i]);
pNext = pInsertPos->right;
while( pNext )
{
pInsertPos = pNext;
pNext = pNext->down;
}
pInsertPos->right = p;
++( M.nzs ); //非零元递增
}
}
}
}
void PrintCSMatrix( const CrossList& M )
{
if ( M.nzs )
{
for ( int i = 0; i < M.rows; ++i )
{
CLNode* p = M.rhead[i].right;
for ( int j = 0; j < M.cols; ++j )
{
//通过行链表头指针进行输出
if ( p && i == p->row && j == p->col )
{
cout << p->e << " ";
p = p->right;
}
else
{
cout << 0 << " ";
}
}
cout << endl;
}
}
}
void DestroyCSMatrix( CrossList& M )
{
if ( M.cols == 0 || M.rows == 0 )
return;
for ( int i = 0; i < M.cols; ++i )
{
CLNode* pPre = NULL;
CLNode* pCur = NULL;
pCur = (&M.chead[i])->down;
while( pCur )
{
pPre = pCur;
pCur = pCur->down;
delete pPre;
}
}
ResetCSMatrix( M );
}
int main()
{
CrossList M;
CreateCSMatrix( M );
cout << endl;
cout << "稀疏矩阵M为:" << endl;
PrintCSMatrix( M );
DestroyCSMatrix( M );
return 0;
}
数据结构:稀疏矩阵的十字链表存储
原创
©著作权归作者所有:来自51CTO博客作者shanql的原创作品,请联系作者获取转载授权,否则将追究法律责任
提问和评论都可以,用心的回复会被更多人看到
评论
发布评论
相关文章
-
【数据结构】特殊矩阵的压缩存储
【数据结构】第三章——栈、队列与数组详细介绍特殊矩阵的压缩存储……
数据结构 C语言 矩阵 压缩存储 数组 -
【数据结构】链式家族的成员——循环链表与静态链表
【数据结构】第二章——线性表(8)详细介绍了循环链表与静态链表的相关内容……
数据结构 C语言 循环链表 静态链表 -
稀疏矩阵的十字链表存储表示
稀疏矩阵,十字链表
稀疏矩阵 十字链表 -
数据结构:图(十字链表存储 c++实现)
有没有可能把邻接表与逆邻接表结合起来呢?
List 邻接表 有向图