十字链表的实现

/*
*2018.9.12 17:09
*十字链表的实现
*注意rhead和chead都是顺序存储的
*其中的down和right并不指向某个结点
*/
#include<stdio.h>
#include<stdlib.h>

#define COLUMN 5

typedef struct Node{
	int r, c;
	int e;
	struct Node *down, *right;
}Node;

typedef struct ONode {
	int col, row;
	int num;
	Node *chead, *rhead;
}HeadNode;


void create_trimat(int matrix[][COLUMN], int m, int n, HeadNode *trimat);


int main(void) {
	system("COLOR fc");

	int temp[][COLUMN] = {
	{0,0,5,9,0},
	{0,1,2,3,6},
	{0,0,2,0,0},
	{0,3,0,0,6},
	{0,23,6,5,15},
	};

	HeadNode *trimat = (HeadNode *)malloc(sizeof(HeadNode));
	create_trimat(temp, 5, 5, trimat);

	Node *temp_r = trimat->rhead;
	putchar('\n'); putchar('\n');
	for (size_t i = 0; i < 5; i++) {
		temp_r = trimat->rhead[i].right;
		while (temp_r != NULL) {
			printf("%5d", temp_r->e);
			temp_r = temp_r->right;
		}putchar('\n');
	}

	putchar('\n');
	system("pause");
	return 0;
}

void create_trimat(int matrix[][COLUMN], int m, int n, HeadNode *trimat) {
	int not_empty = 0;
	trimat->col = n;
	trimat->row = m;
	

	trimat->rhead = (Node*)malloc(sizeof(Node) * m);
	trimat->chead = (Node*)malloc(sizeof(Node) * n);

	if (!trimat->rhead || !trimat->chead) return;

	for (size_t i = 0; i < m; i++) {
		trimat->rhead[i].c = -1;
		trimat->rhead[i].r = -1;
		trimat->chead[i].e = -1;
		trimat->rhead[i].down = NULL;
		trimat->rhead[i].right = NULL;
	}
	for (size_t i = 0; i < n; i++) {
		trimat->chead[i].c = -1;
		trimat->chead[i].r = -1;
		trimat->chead[i].e = -1;
		trimat->chead[i].down = NULL;
		trimat->chead[i].right = NULL;
	}

	Node *temp_column[COLUMN];
	for (size_t i = 0; i < COLUMN; i++)
		temp_column[i] = &(trimat->chead[i]);

	for (size_t i = 0; i < m; i++){
		Node *p = &(trimat->rhead[i]);
		for (size_t j = 0; j < n; j++){
			if (matrix[i][j] != 0) {
				Node *temp_node = (Node*)malloc(sizeof(Node));
				temp_node->r = i;
				temp_node->c = j;
				temp_node->e = matrix[i][j];
				temp_node->down = NULL;
				temp_node->right = NULL;

				p->right = temp_node;
				p = temp_node;

				temp_column[j]->down = temp_node;
				temp_column[j] = temp_node;

				not_empty++;
			}
		}
	}
	trimat->num = not_empty;
}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值