C/C++: 三元组相加/相乘

/**
*
* 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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值