gpt4 book ai didi

c - 链表追加最后一次不起作用

转载 作者:太空宇宙 更新时间:2023-11-04 02:33:00 24 4
gpt4 key购买 nike

为什么最后一个追加调用不起作用?我必须在这里添加一些垃圾,因为它提示我的帖子主要是代码,我希望现在已经足够详细了。

typedef struct node {
int val;
struct node * next;
} node_t;

void append_node(node_t * head, int val) {
node_t * current = head;

while(current->next != NULL) {
current = current->next;
}

current->next = malloc(sizeof(node_t));
if(current->next == NULL)
printf("err");

current = current->next;
current->val = val;
current->next = NULL; //malloc(sizeof(node_t));
}

void print_list(node_t * head) {
node_t * current = head;
while(current->next != NULL) {
printf("%d ", current->val);
current = current->next;
}
printf("\n");
}

int main() {
node_t * list = malloc(sizeof(node_t));
list->val = 1;
list->next = NULL;
append_node(list,12);
append_node(list,14);
append_node(list,17);

print_list(list);
return 0;
}

输出:

1 12 14

最佳答案

问题出在您的打印功能上。您不打印最后一个元素。

#include <stdio.h>
#include <stdlib.h>
typedef struct node {
int val;
struct node * next;
} node_t;

void append_node(node_t * head, int val) {
node_t * current = head;

while(current->next != NULL) {
current = current->next;
}

current->next = malloc(sizeof(node_t));
if(current->next == NULL)
printf("err");

current = current->next;
current->val = val;
current->next = NULL; //malloc(sizeof(node_t));
}

void print_list(node_t * head) {
node_t * current = head;
while(current!= NULL) {
printf("%d ", current->val);
current = current->next;
}
printf("\n");
}

int main() {
node_t * list = malloc(sizeof(node_t));
list->val = 1;
list->next = NULL;
append_node(list,12);
append_node(list,14);
append_node(list,17);

print_list(list);
return 0;
}

关于c - 链表追加最后一次不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40947224/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com