使用三元组实现稀疏矩阵的建立、逆转、乘法。
乘法没有使用附加向量,是自己想得。有错误请谅解。性能可能没有书上介绍的好。
代码如下:(本代码只经过本人的简单测试,可能存在问题。请相信自己的能力,敢于质疑。欢迎提供更好的、更快、更简洁的代码或者方法和指出错误。在ubuntu12.04使用gcc4.6.3版本编译,在vc中如出现错误,请谅解。)
/*
*created by Reage at 2012 November 29
*description: 稀疏矩阵实现,包含乘法、逆转
*
*blog:http://blog.csdn.net/rentiansheng
*/
#include <stdio.h>
#include <stdlib.h>
#define LINE print_split(20)
typedef struct triple{
int i,j;//行列
int value;
}triple;
typedef struct matrix{
triple * head;
int row,column,count;//矩阵的行、列、稀疏矩阵的元素个数
}matrix;
/*
*description:判断某一个位置是否已经存在元素
*parameter:
* x:行坐标
* y:列坐标
* count:要查找的元素个数,如果为0表示全部,否则是count的值
*result:找到返回1,未找到返回0
*/
int find_ item (matrix *m, int x, int y, int count ){
triple *tp = m->head;
if ( !count || count > m->count ) count =m->count;
int i;
for (i = 0; i < count - 1; i++){
if ( tp->i == x && tp->j == y) return 1;
tp++;
}
return 0;
}
/*
*初始化稀疏矩阵
*/
void init_matrix (matrix *m, int row, int column, int count){
// if (m->head) free(m->head);//如果矩阵已经存在,释放原有的数据空间
m->head = (triple *) malloc ( count * sizeof (triple));
if (!m->head){
printf("Allocate memory failed!application