简单的链表在C中显示相同的数字

时间:2018-03-10 17:05:32

标签: c linked-list

我刚刚开始学习链表,我正在尝试制作链表。

#include <stdio.h>
#include <stdlib.h>

typedef struct ListNode {
    int value;
    struct ListNode *next;
} ListNode;

问题是我在列表的开头插入了一个函数,但是当我尝试用显示函数显示所有内容时,它进入一个无限循环,显示我插入列表的最后一个数字。

void insertBEG(ListNode **list, int elem) {

    ListNode *node = (ListNode *)malloc(sizeof(ListNode));
    node->value = elem;
    node->next = NULL;  // create a new node

    if((*list) == NULL){
        (*list) = node;
        node->next = NULL;
        return;
    }
    node->next = (*list);
    (*list) = node;
}

void display(ListNode **list) {
    ListNode *current = (*list);

    if(current == NULL) return;

    while( current != NULL) {
        printf("The element in the list is: %d\n", current->value);
    }
}

int main () {
    ListNode *head = NULL;
    int i;

    for(i = 0; i < 20; i++) {
        insertBEG(&head, i);
    }

    display(&head);

    return 0;
}

输出:

The element in the list is: 19
The element in the list is: 19
x infinte times

我真的不明白为什么会这样。如果有人可以提供帮助,我将非常感激。

1 个答案:

答案 0 :(得分:3)

您的display仅打印头部,您错过了循环中的current = current->next

void display(ListNode **list) {
    ListNode *current = (*list);

    if(current == NULL) return;

    while( current != NULL) {
        printf("The element in the list is: %d\n", current->value);
        current = current->next; // <-- you missed that
    }
}

所以函数永远停留在while循环中。

相关问题