1
爲什麼上次追加呼叫不起作用?我必須在這裏添加一些垃圾,因爲它抱怨我的帖子主要是代碼,我希望現在有足夠的細節。鏈接列表追加最後一次不起作用
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
你介意顯示打印功能嗎? –
(因爲它以某種方式無法打印最後一個節點) –
@PaulStelian同意... add函數中的邏輯看起來是正確的。 –