Home > Software design >  Iteration through a linked list against itself not working as expected
Iteration through a linked list against itself not working as expected

Time:05-21

I am very sorry if this has been answered before.

Upon running this code I wish to iterate through a linked list and then iterate through it again for each element in the list. I would love to know what on earth I am doing wrong here. Thanks.

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


typedef struct node {
    int data;
    struct node *next;
} node_t;

node_t * push_end(node_t * end, int data) {
    end->next = (node_t *) malloc(sizeof(node_t));
    end->next->data = data;
    end->next->next = NULL;
    return end->next;
}

int main() {

    node_t * head = (node_t *) malloc(sizeof(node_t));
    head->data = 0;
    head->next = NULL;

    node_t * end = head;

    end = push_end(end, 1);
    end = push_end(end, 2);

    node_t *i_obj = head;
    node_t *j_obj = head;

    while(i_obj != NULL) {
        while(j_obj != NULL) {
            printf("%d, %d | ", i_obj->data, j_obj->data);
            j_obj = j_obj->next;
        }
        i_obj = i_obj->next;
    }
}

Expected output: 0, 0 | 0, 1 | 0, 2 | 1, 0 | 1, 1 | 1, 2 | 2, 0 | 2, 1 | 2, 2 |

Actual output: 0, 0 | 0, 1 | 0, 2 |

CodePudding user response:

You need to reset j_obj to point to the head node for each iteration of i_obj. As it stands, j_obj becomes NULL at the completion of the first time through the inner loop and stays NULL, so the inner loop is never executed 2nd or 3rd time through.

Change the latter part of your code as follows:

node_t *i_obj = head;

while(i_obj != NULL) {
    node_t *j_obj = head;
    while(j_obj != NULL) {
        printf("%d, %d | ", i_obj->data, j_obj->data);
        j_obj = j_obj->next;
    }
    i_obj = i_obj->next;
}

Another, arguably clearer, way to write this would be:

for (node_t *p = head; p; p = p->next) {
    for (node_t *q = head; q; q = q->next) {
        printf("%d, %d | ", p->data, q->data);
    }
}
  • Related