赞
踩
#include<stdio.h>
#include<stdlib.h>
#define MAX 12
typedef int datatype;
typedef struct
{
int i, j; //行号、列号
datatype v; //元素值
} node;
typedef struct
{
int m, n, t; //行数,列数,非零元素个数
node data[MAX]; //三元组表
}spmatrix;
spmatrix *Create() //创建一个3行4列的稀疏矩阵
{
int m , n , k = 0, t = 0 , z ;
datatype element;
spmatrix *matrix;
printf("请分别输入你要创建的稀疏矩阵的行号和列号:\n");
scanf("%d %d",&m,&n);
matrix =new spmatrix; //创建一个稀疏矩阵a
matrix->m = m;
matrix->n = n;
z=m*n;
printf("输入%d个整数:\n",z);
while (k < m*n)
{
scanf("%d", &element);
if (element != 0)
{
matrix->data[t].i = k / n;
matrix->data[t].j = k % n;
matrix->data[t].v = element;
t++;
}
k++;
}
matrix->t = t;
return matrix;
}
spmatrix *TransMat(spmatrix *a) //稀疏矩阵的转置
{
int p, q, k = 0;
spmatrix *b;
b =new spmatrix; //为矩阵b分配内存空间
b->m = a->n;
b->n = a->m;
b->t = 0;
if (a->t == 0)
return b;
for (p = 0; p < a->n; p++)//put the a's j to the b's i,as the same
for (q = 0; q < a->t; q++)
if (a->data[q].j == p)
{
b->data[k].i = a->data[q].j;
b->data[k].j = a->data[q].i;
b->data[k].v = a->data[q].v;
k++;
}
b->t = k;
return b;
}
void Output(spmatrix *a)
{
int k = 0;
for (int i = 0; i < a->m; i++)
{
for (int j = 0; j < a->n; j++)
{
if (i == a->data[k].i && j == a->data[k].j)
{
printf("%d ", a->data[k].v);
k++;
}
else
printf("%d ", 0);
}
printf("\n");
}
}
void main()
{
spmatrix *a = Create();
spmatrix *b = TransMat(a);
printf("原矩阵:\n");
Output(a);
printf("转置矩阵:\n");
Output(b);
}
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。