十字链表表示稀疏矩阵

该程序实现了使用十字链表表示稀疏矩阵,并支持矩阵的初始化、插入非零元素、打印矩阵和释放内存。

参考图片

Image

代码

#include<stdio.h>
#include<stdlib.h>
#define MAXM 30 
struct Node{
	int row;
	int col;
	int val;
	struct Node* right;
	struct Node* down;
}; 
struct CrossList{
	struct Node* rhead[MAXM];
	struct Node* chead[MAXM];
	int m; //矩阵的行数 
	int n; //矩阵的列数 
	int total;
};
/**
 * 初始化十字链表
 * 
 * obj:指向十字链表的指针
 * m:矩阵的行数
 * n:矩阵的列数
 */
void initList(struct CrossList* obj, int m, int n){
	obj->m = m;
	obj->n = n;
	obj->total = 0;
	for(int i = 0; i < m; i++)obj->rhead[i] = NULL;
	for(int i = 0; i < n; i++)obj->chead[i] = NULL;
} 
/**
 * 向十字链表中添加一个非零元素
 * 
 * obj:指向十字链表的指针
 * m:非零元素所在的行索引
 * n:非零元素所在的列索引
 * v:非零元素的值
 */
void addList(struct CrossList* obj, int m, int n,int v){
	struct Node* p = (struct Node*)malloc(sizeof(struct Node));
	p->row = m;
	p->col = n;
	p->val = v;
	p->right = NULL;
	p->down = NULL;
	obj->total ++;
	
	struct Node* cur;
	cur = obj->rhead[m];
	if(!cur){
		obj->rhead[m] = p;
	} else {
		while(cur->right){
			cur = cur->right;
		}
		cur->right = p;
	}
	
	cur = obj->chead[n];
	if(!cur){
		obj->chead[n] = p;
	} else {
		while(cur->down){
			cur = cur->down;
		}
		cur->down = p;
	}
}
/**
 * 打印十字链表表示的稀疏矩阵
 * 
 * obj:指向十字链表的指针
 */
void printList(struct CrossList* obj){
	for(int i = 0; i < obj->m; i++){
		struct Node* tmp = obj->rhead[i];
		
		for(int j = 0; j < obj->n; j++){
			if(tmp && tmp->col == j){
				printf("%d ", tmp->val);
				tmp = tmp->right;
			} else {
				printf("  ");
			}
		}
		printf("\n");
	}
}

/**
 * 释放十字链表占用的内存
 * 
 * obj:指向十字链表的指针
 */
void freeList(struct CrossList* obj){
	for(int i = 0; i < obj->m; i++){
		struct Node* cur = obj->rhead[i];
		while(cur){
			struct Node* tmp = cur;
			free(tmp);
			cur = cur->right;
		}
		obj->rhead[i] = NULL;
	}
	for(int i = 0; i < obj->n; i++){
		obj->chead[i] = NULL;
	}
}
int main(){
	// 动态分配十字链表结构体
	struct CrossList* b = (struct CrossList*)malloc(sizeof(struct CrossList));
	
	int m, n;
	scanf("%d %d",&m, &n);
	initList(b, m, n);
	
	for(int i = 0; i < m; i++){
		for(int j = 0; j < n; j++){
			int x;
			scanf("%d", &x);
			if(x == 0)continue;
			addList(b, i, j, x);
		}
	}
	
	printList(b);
	freeList(b);
	free(b);
}
/*
test1
3 3
0 1 0
1 0 0
0 0 1
*/

运行结果

Image