0
今天我有C考试,并且我无法从链接列表中删除第一个节点。在我的情况下,它删除第一个元素,但头仍然指向第一个节点'0'。我现在坐在那里搜索解决方案,但找不到任何东西。功能头(struct t_node *delete_first(struct t_node *head)
)已由教授提供。无法从链接列表中删除第一个节点
#include <stdio.h>
#include <stdlib.h>
struct t_node {
int number;
struct t_node *next;
};
struct t_node * insert (struct t_node *head, int num){
struct t_node * new_node = malloc(sizeof(struct t_node));
new_node->number = num;
new_node->next = head;
return new_node;
}
void printlistvalues(struct t_node *head){
while (head != NULL){
printf("%d\n", head->number);
head = head->next;
}
}
struct t_node *delete_first(struct t_node *head){
struct t_node *help = head;
head = head->next;
free(help);
return head;
}
int main(){
struct t_node *list = NULL;
list = insert(list, 10);
list = insert(list, 20);
list = insert(list, 30);
list = insert(list, 40);
list = insert(list, 50);
printlistvalues(list);
printf("\n");
delete_first(list);
printlistvalues(list);
return 0;
}
你不更新列表指针您删除节点之后。尝试'list = delete_first(list);'。 – owacoder
为便于我们理解和可读性人类,请一致缩进。在每个开口大括号后面缩进{'。在每个右括号前加上unindent。每个缩进级别始终缩进相同数量(建议使用4个空格,因为即使使用可变宽度的字体,也可以看到宽度足够大的空间) – user3629249