#include<iostream>
#define ROW 5
#define COL 5
using namespace std;
typedef int DataType;
typedef struct node {
DataType data;
int row, col;
struct node*link;
}LinkNode;
typedef struct {
LinkNode*first;
int len;
}LinkList;
void LinkListInit(LinkList*L)
{
L->first = new LinkNode;
L->first->link = NULL;
L->len = 0;
}
LinkList*SparseMatrix(DataType S[][COL])
{
LinkList*L = new LinkList;
LinkListInit(L);
LinkNode*M = L->first;
for(int i=0;i<ROW;i++)
for (int j = 0;j < COL;j++)
if(S[i][j])
{
LinkNode*NewNode = new LinkNode;
NewNode->row = i;
NewNode->col = j;
NewNode->data = S[i][j];
NewNode->link = M->link;
M->link = NewNode;
M = NewNode;
L->len++;
}
return L;
}
void Print(LinkList*L)
{
LinkNode*M = L->first->link;
while(M!=NULL)
{
cout << "col:" << M->col << " row:" << M->row << " data:" << M->data << endl;
M = M->link;
}
}
/*
int main()
{
DataType M[ROW][COL];
int k;
for (int i = 0;i < ROW;i++)
for (int j = 0;j < COL;j++)
if ((k = rand() % 10) > 6)
M[i][j] = k;
else
M[i][j] = 0;
LinkList*MP = SparseMatrix(M);
Print(MP);
system("pause");
}
*/
C++稀疏矩阵的链表表示
最新推荐文章于 2022-06-09 09:22:42 发布