Nathan Murillo
Nathan Murillo

Reputation: 59

While cycle isn't reaching the end of a linked list

I'm learning about data structures and I'm trying to create a linked list. My problem is that one of my two while cycles aren't reaching the end of the linked list (it stops in the first element). They're not exactly equal, but they're very similar; the first cycle (the working one) runs while the current list pointer isn't null, and the second runs while the the next list pointer isn't null. The compiler isn't showing any errors and the program doesn't stop working when opened. Also is important to say that this isn't my main code, it's a test code that I wrote to try to solve the problem myself (unfortunately, without success) - but it serves to illustrate the problem.

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

typedef struct List {
    int data;
    struct List *next;
} List;

int main(void) {
    system("cls");

    List *hook    = (List *) malloc(sizeof(List)),
         *root1   = (List *) malloc(sizeof(List)),
         *root2   = (List *) malloc(sizeof(List)),
         *root3   = (List *) malloc(sizeof(List)),
         *item    = (List *) malloc(sizeof(List)),
         *current = (List *) malloc(sizeof(List));

    hook->data = -20;
    hook->next = root1;

    root1->data = 10;
    root1->next = root2;

    root2->data = 20;
    root2->next = root3;

    root3->data = 30;
    root3->next = NULL;

    current = hook;
    while (current != NULL) {
        printf("\"First while\" data: %i\n", current->data);
        current = current->next;
    }
    // In this while cycle, the code goes through all the items of the linked list and print their data values correctly

    printf("\"Hook\" next: %i\n", hook->next);
    current = hook;

    printf("\"Current->next\" next: %i\n", current->next->next);

    while (current->next != NULL) {
        current->next = current->next->next;
    }
    // On the other hand, in this while cycle the code stops in the first element of the list (hook);
    // consequently, it prints the first data value, but the intention was to get in the end of the list and print the last value

    printf("\"Second while\" data: %i\n", current->data);
    
    return 0;
}

Picture of the terminal with the program output

"Hook" and "Current->next" are purposely being displayed with "%i", just to verify if they aren't null. What exactly am I doing wrong?

Upvotes: 0

Views: 192

Answers (1)

Some programmer dude
Some programmer dude

Reputation: 409356

With the loop

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

You modify the list, effectively removing all but the first node from the list.

If you want to only iterate over it to get the last node, you need to update current like normal:

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

Upvotes: 4

Related Questions