对于赋值,我们必须在C中实现一个二维链表。 我的想法是自己创建几个链接列表,并将其头部链接在一起。
这是我想出的代码,不幸的是它无法正常工作。 当我尝试从树节点开始遍历结果时,没有打印任何内容。
有人能指出正确的方向吗?
#include <stdio.h>
#include <stdlib.h>
struct cell{
int value;
struct cell *next;
};
struct head {
int value;
struct head *next;
struct cell *cells;
};
struct head *current_head, *new_head;
struct cell *current_cell, *new_cell;
int i;
int j;
void grid_init(int num_rows,int num_columns){
for (i=0; i<num_rows-1;i++) {
struct cell * current_cell = (struct cell* ) malloc (sizeof(struct cell));
current_head->cells = current_cell;
for (j=0; j<num_columns-1; j++) {
struct cell* new_cell = (struct cell* ) malloc (sizeof(struct cell));
current_cell->next = new_cell;
current_cell->value=j;
current_cell = new_cell;
}
struct head* new_head = (struct head *) malloc (sizeof(struct head));
current_head->next = new_head;
current_head->value=i;
current_head = new_head;
}
};
void print_grid(){
struct head* temp = current_head;
struct cell* tempcell = current_cell;
while(temp->next!=NULL){
tempcell = temp->cells;
while(tempcell->next!=NULL){
tempcell = temp->cells;
printf("%i", tempcell->value);
tempcell = tempcell->next;
}
temp = temp->next;
}
};
int main(){
current_head = (struct head *) malloc (sizeof(struct head));
int a=5;
int b=5;
grid_init(a,b);
print_grid();
};