ginger
ginger

Reputation: 63

Simple linked list displaying the same number in C

I just started to learn about linked list and I'm trying to make one.

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

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

The problem is that I made a function to insert at the begining of the list, but when I try to display everything with the display function, it enters an infinite loop displaying the last number I inserted the list.

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 output:

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

I really don't understand why this is happening. If anybody can help I would be truly grateful.

Upvotes: 0

Views: 54

Answers (1)

Pablo
Pablo

Reputation: 13580

Your display is printing only the head, you missed a current = current->next in the loop

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

so the function was stuck in the while loop forever.

Upvotes: 3

Related Questions