简体   繁体   中英

Linked list append doesn't work the last time

Why does the last append call not work? I have to add some garbage here because it is complaining that my post is mostly code, I hope it is enough details by now.

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;
}

Output:

1 12 14

The problem is in your print function. You don't print the last element.

#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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM