/**
*
* Althor: Hacker Hao
* Create:
*
*/
#include<iostream>
using namespace std;
typedef int ElemType;
#define M 4 //行
#define N 4 //列
#define MaxSize 6 //非零元素
//定义
typedef struct mtxn
{
int row; //行号
int col; //列号
struct mtxn* right, * down; //向右和向下的指针
union
{
ElemType value; //非零元素值
struct mtxn* link; //指向下一个头结点
}tag;
}MatNode;
//创建
void Create_2(MatNode*& mh, ElemType a[M][N])
{
int i, j;
MatNode* h[MaxSize], * p, * q, * r;
mh = (MatNode*)malloc(sizeof(MatNode)); //创建头节点
mh->row = M;
mh->col = N;
r = mh;
for (i = 0; i < MaxSize; i++) //尾插
{
h[i] = (MatNode*)malloc(sizeof(MatNode));
h[i]->down = h[i]->right = h[i];
r->tag.link = h[i];
r = h[i];
}
r->tag.link = mh; //循环链表
for (i = 0; i < M; i++)
{
for (j = 0; j < N; j++)
{
if (a[i][j] != 0)
{
p = (MatNode*)malloc(sizeof(MatNode));
p->row = i;
p->col = j;
p->tag.value = a[i][j];
q = h[i];
while (q->right != h[i] && q->right->col < j)
{
q = q->right;
}
p->right = q->right;
q->right = p;
q = h[j];
while (q->down != h[j] && q->down->row < i)
{
q = q->down;
}
p->down = q->down;
q->down = p;
}
}
}
}
//输出
void DispMat_2(MatNode* mh)
{
MatNode* p, * q;
cout << "行为:" << 3 << " " << "列为:" << 3 << endl;
p = mh->tag.link;
while (p != mh)
{
q = p->right;
while (p != q) //输出一行非零元素
{
cout << q->row << '\t' << q->col << '\t' << q->tag.value << endl;
q = q->right;
}
p = p->tag.link;
}
}
//相乘
void MulMat_2(ElemType a[M][N], ElemType b[N][M], ElemType c[M][M])
{
int i;
int j;
int k;
int temp;
for (i = 0; i < M; i++)
{
for (j = 0; j < N; j++)
{
temp = 0;
for (k = 0; k < 4; k++)
{
temp = temp + a[i][k] * b[k][j];
}
c[i][j] = temp;
}
}
}
int main()
{
MatNode* td, * tf;
ElemType a[M][N] = { 1, 0, 3, 0, 0, 1, 0, 0, 0, 0, 1, 0};
ElemType b[N][M] = { 3, 0, 0, 0, 4, 0, 0, 0, 1, 0, 0, 0};
ElemType c[N][N] = { 0 };
cout << "矩阵a,b相乘:" << endl;
MulMat_2(a, b, c);
Create_2(tf, c);
DispMat_2(tf);
cout << endl;
return 0;
}
C/C++: 三元组相加/相乘
最新推荐文章于 2024-10-02 08:00:00 发布