这是我的代码(在链表上工作):
typedef struct node {
int data;
struct node_t* next;
} node_t;
typedef struct list{
node_t* head;
} list_t;
node_t* create_node(void){
node_t* tmp = malloc(sizeof(node_t));
if (tmp == NULL){
fprintf(stderr, "Error while allocating memory for node\n");
exit(EXIT_FAILURE);
}
return tmp;
}
void list_insert(list_t* list, node_t* node, int data){
if (node == NULL){
node_t* new = create_node();
new->next = list->head;
list->head = new;
new->data = data;
}
else{
node_t* current = list->head;
while(current != node){
current = current->next;
}
node_t* new = create_node();
new->next = current->next;
current->next = new;
new->data = data;
}
}
我确实在 list_insert 函数中收到一些警告,但我无法弄清楚它们的原因。如果作为参数传递的 node
为 NULL
,则此函数应在开头插入一个新节点,否则应在 node
之后插入一个新节点> 作为参数传递。
在这段代码中:
if (node == NULL){
node_t* new = create_node();
new->next = list->head;
list->head = new;
new->data = data;
}
赋值 new->next = list->head;
不正确。有什么猜测吗?
最佳答案
在你定义的struct node
中:
typedef struct node {
int data;
struct node_t* next;
} node_t;
您将next
定义为指向struct node_t
的指针,但是没有这样的类型。你想要struct node
:
typedef struct node {
int data;
struct node* next;
} node_t;
关于c - c - 链表中指针的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54675424/