C语言数据结构稀疏矩阵十字链表
时间: 2023-11-26 13:43:11 浏览: 100
稀疏矩阵的十字链表是一种用于压缩稀疏矩阵的数据结构。它通过链表的方式来存储矩阵中非零元素的位置和值,并且可以快速地进行插入和删除操作。在C语言中,可以使用结构体和指针来实现稀疏矩阵的十字链表。具体实现如下:
```
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int row;
int col;
int value;
struct Node* right;
struct Node* down;
} Node;
typedef struct CrossList {
Node* rhead;
Node* chead;
int rows;
int cols;
int nums;
} CrossList;
void InitCrossList(CrossList* crosslist, int rows, int cols);
void InsertCrossList(CrossList* crosslist, int row, int col, int value);
void PrintCrossList(CrossList* crosslist);
void InitCrossList(CrossList* crosslist, int rows, int cols) {
crosslist->rhead = (Node*)malloc(sizeof(Node) * rows);
crosslist->chead = (Node*)malloc(sizeof(Node) * cols);
crosslist->rows = rows;
crosslist->cols = cols;
crosslist->nums = 0;
for (int i = 0; i < rows; i++) {
crosslist->rhead[i].right = NULL;
}
for (int i = 0; i < cols; i++) {
crosslist->chead[i].down = NULL;
}
}
void InsertCrossList(CrossList* crosslist, int row, int col, int value) {
if (row >= crosslist->rows || col >= crosslist->cols) {
return;
}
Node* node = (Node*)malloc(sizeof(Node));
node->row = row;
node->col = col;
node->value = value;
Node* p = &crosslist->rhead[row];
while (p->right && p->right->col < col) {
p = p->right;
}
if (p->right && p->right->col == col) {
p->right->value = value;
free(node);
} else {
node->right = p->right;
p->right = node;
}
p = &crosslist->chead[col];
while (p->down && p->down->row < row) {
p = p->down;
}
if (p->down && p->down->row == row) {
p->down->value = value;
} else {
node->down = p->down;
p->down = node;
}
crosslist->nums++;
}
void PrintCrossList(CrossList* crosslist) {
printf("稀疏矩阵的十字链表表示:\n");
for (int i = 0; i < crosslist->rows; i++) {
Node* p = crosslist->rhead[i].right;
for (int j = 0; j < crosslist->cols; j++) {
if (p && p->col == j) {
printf("%d ", p->value);
p = p->right;
} else {
printf("0 ");
}
}
printf("\n");
}
}
int main() {
CrossList crosslist;
int rows, cols;
printf("请输入稀疏矩阵的行数和列数:");
scanf("%d %d", &rows, &cols);
InitCrossList(&crosslist, rows, cols);
int row, col, value;
printf("请输入稀疏矩阵中非零元素的行、列和值(以-1 -1 -1结束):\n");
while (1) {
scanf("%d %d %d", &row, &col, &value);
if (row == -1 && col == -1 && value == -1) {
break;
}
InsertCrossList(&crosslist, row, col, value);
}
PrintCrossList(&crosslist);
return 0;
}
```
阅读全文