开发进行时...

crazy coder

Avatar

sparse matrix

稀疏矩阵

三元组表示法
伪地址表示法A[i][j]=> (i-1)*j
十字链表方法
struct matnode
{
int row, col;
struct matnode * right,* down;
union
{
int val;
struct matnode *next;
}tag;
};

sparsematrix.c


#include <stdlib.h>
#include <stdio.h>

struct matnode
{
	int row, col;
	struct matnode * right,* down;
	union
	{
		int val;
		struct matnode *next;

	}tag;
};
typedef struct matnode matrix;
typedef matrix *ten_matrix;


ten_matrix createmat()
{
	int m,n,t,s,i,r,c,v;
	ten_matrix h[100],p,q;// *h[] is header point of ten-link-table'row

	printf("行数m, 列数n,非零元个数t:");
	scanf("%d,%d,%d",&m,&n,&t);

	p = (ten_matrix)malloc(sizeof(matrix));
	h[0]=p;
	p->row=m;
	p->col=n;
	s=m>n?m:n;
	for(i=1;i<=s;i++)
	{
		p = (ten_matrix)malloc(sizeof(matrix));
		h[i]=p;
		h[i-1]->tag.next=p;
		p->row = p->col=0;
		p->down=p->right=p;
	}
	h[s]->tag.next=h[0];
	for(i=1;i<=t;i++)
	{
		printf("\t第%d个元素(行号r,列号c,值v):",i);
		scanf("%d,%d,%d",&r,&c,&v);
		p = (ten_matrix) malloc(sizeof(struct matnode));
		p->row = r;
		p->col = c;
		p->tag.val = v;
		q = h[r];
		while(q->right != h[r] && q->right->col < c)
			q = q->right;
		p->right = q->right;
		q->right = p;
		q = h[c];
		while(q->down != h[c] && q->down->row < r)
			q = q->down;
		p->down = q->down;
		q->down = p;
	}
	return(h[0]);

}


int prmat(ten_matrix hm)
{
	ten_matrix p,q;
	printf("按行表输出矩阵元素:\n");
	printf("row=%d col=%d\n",hm->row, hm->col);
	p = hm->tag.next;
	while(p != hm)
	{
		q = p->right;
		while(p != q)
		{
			printf("\t%d, %d, %d\n", q->row, q->col, q->tag.val);
			q = q->right;
		}
		p = p->tag.next;
	}
}

int findmat(ten_matrix hm, int x, int *rown, int *coln)
{
	ten_matrix p, q;
	p = hm->tag.next;
	while(p != hm)
	{
		q = p->right;
		while(p != q)
		{
			if(q->tag.val == x)
			{
				*rown = q->row;
				*coln = q->col;
				return(1);
			}
			q = q->right;
		}
		p = p->tag.next;
	}
	return(0);
}


int main()
{
	ten_matrix hm;
	hm = createmat();
	prmat(hm);
}