您的位置:首页 > 理论基础 > 数据结构算法

数据结构:稀疏矩阵的十字链表存储

2015-05-08 13:49 309 查看
//-----------------稀疏矩阵的十字链表存储-------------------

#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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: