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