#include <iostream>
#include <iomanip>
using namespace std;
typedef int ElemType;
typedef struct Node{
int i, j;//该结点非零元的行列下标
ElemType e;//该结点非零元的值
struct Node* right, * down;//该十字链表结点的右指针与下指针
}OLNode,*OLink;//十字链表结点
typedef struct {
OLink* rhead, * chead;//行(列)链表的头指针数组
int mu, nu, tu;//十字链表的行数、列数、非零元个数
}CrossList;//十字链表
bool InitTSMatrix(CrossList& M);//初始化十字链表
bool CreateTSMatrix(CrossList& M);//构造十字链表
bool TraverseTSMatrix(CrossList M);//遍历十字链表稀疏矩阵
bool SearchTSMatrix(CrossList M, ElemType e);//搜索稀疏矩阵中值为e的非0元素
bool InitTSMatrix(CrossList& M) {
cout << "输入矩阵行数、列数:";
cin >> M.mu >> M.nu;
M.tu = 0;
M.rhead = new OLink[M.mu + 1]; if (!M.rhead)return 0;//下标从1开始
M.chead = new OLink[M.nu + 1]; if (!M.chead)return 0;
for (int i = 1; i <= M.mu; i++)
M.rhead[i] = NULL;
for (int i = 1; i <= M.nu; i++)
M.chead[i] = NULL;
return 1;
}
bool CreateTSMatrix(CrossList& M) {
cout << "输入i j e(输入0表示结束): " << endl;
while (1) {
int i, j, e;
cin >> i;
if (i == 0)break;
cin >> j >> e;
OLink temp = new OLNode;
if (!temp)return 0;
temp->i = i;
temp->j = j;
temp->e = e;
//插入行链表
if (M.rhead[i] == NULL || M.rhead[i]->j > j) {
temp->right = M.rhead[i];
M.rhead[i] = temp;
}
else {
OLink p = M.rhead[i];
while (p->right && p->right->j < j)
p = p->right;
temp->right = p->right;
p->right = temp;
}
//插入列链表
if (M.chead[j] == NULL || M.chead[j]->i > i) {
temp->down = M.chead[j];
M.chead[j] = temp;
}
else {
OLink p = M.chead[j];
while (p->down && p->down->i < i)
p = p->down;
temp->down = p->down;
p->down = temp;
}
M.tu++;
}
return 1;
}
bool TraverseTSMatrix(CrossList M) {
if (M.tu == 0)return 0;
for (int i = 1; i <= M.mu; i++) {
OLink temp = M.rhead[i];
while (temp) {
cout << setw(4) << temp->i;
cout << setw(4) << temp->j;
cout << setw(6) << temp->e << endl;
temp = temp->right;
}
}
return 1;
}
bool SearchTSMatrix(CrossList M, ElemType e) {
int flag = 0;
for (int i = 1; i <= M.mu; i++) {
OLink temp = M.rhead[i];
while (temp) {
if (temp->e == e) {
cout << "i=" << temp->i;
cout << ", j=" << temp->j;
cout << ", e=" << temp->e << endl;
flag = 1;
}
temp = temp->right;
}
}
if (flag)
return 1;
return 0;
}
int main()
{
CrossList M;
InitTSMatrix(M);
if (!CreateTSMatrix(M)) {
cout << "稀疏矩阵十字链表创建失败!" << endl;
return 1;
}
cout << "稀疏矩阵为:\n";
cout << "---------------\n";
cout << " i j e\n";
cout << "---------------\n";
if (!TraverseTSMatrix(M)) {
cout << "该矩阵没有非零元素!" << endl;
return 2;
}
cout << "---------------" << endl;
ElemType e;
cout << "输入要查找的矩阵元素:\n";
cin >> e;
cout << "查询情况如下:\n";
if (!SearchTSMatrix(M, e)) {
cout << "没有找到该元素!" << endl;
}
return 0;
}
实验样例: