十字链表的实现
作者:互联网
/*
*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;
}
标签:Node,temp,实现,链表,int,trimat,十字,chead,rhead 来源: https://blog.csdn.net/ydeway/article/details/101039672