Home > Enterprise >  Linked list unable to print all elements
Linked list unable to print all elements

Time:05-30

I'm trying to print the linked list to which I prompt for user input. This code below is not printing the whole list, only the last element at a time. I don't seem to find the bug. Can you please take a look at it?

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

struct Node {
    int data;
    struct Node *next;
};

struct Node *head;

void Insert(int x) {
    struct Node *temp = (struct Node *)malloc(sizeof(struct Node));
    temp->data = x;
    temp->next = NULL;
    head = temp;
};

void Print() {
    struct Node *temp = head;
    printf("Linked list is: ");
    while (temp != NULL) {
        printf("%d ", temp->data);
        temp = temp->next;
    }
    printf("\n");
};

int main() {
    head = NULL;
    int i, x;
    for (i = 1; i <= 10; i  ) {
        if (i == 1) {
            printf("Enter 1st number: \n");
        } else if (i == 2) {
            printf("Enter 2nd number: \n");
        } else {
            printf("Enter %dth number: \n", i);
        }
        scanf("%d", &x);
        Insert(x);
        Print();
    }
}

CodePudding user response:

temp->next = NULL; is the culprit. It should be temp->next = head;.

Another (more cornercase) issue is that your code fails to check for errors in malloc and scanf.

CodePudding user response:

When you insert the new node, you do not link the rest of the list, instead of temp->next = NULL; you should write

    temp->next = head;

To ensure defined behavior, you should check for memory allocation failure and invalid input.

Also remove the dummy ; after the function bodies.

Here is a modified version:

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

struct Node {
    int data;
    struct Node *next;
};

struct Node *head;

int Insert(int x) {
    struct Node *temp = malloc(sizeof(*temp));
    if (temp) {
        temp->data = x;
        temp->next = head;
        head = temp;
        return 1;
    } else {
        return 0;
    }
}

void Print(void) {
    struct Node *temp = head;
    printf("Linked list is: ");
    while (temp != NULL) {
        printf("%d ", temp->data);
        temp = temp->next;
    }
    printf("\n");
}

int main() {
    static char suffix[4][3] = { "th", "st", "nd", "rd" };
    int i, x;
    for (i = 1; i <= 10; i  ) {
        int suff = (i >= 1 && i <= 3) ? i : 0;
        printf("Enter %d%s number:\n", i, suffix[suff]);
        if (scanf("%d", &x) != 1) {
            fprintf(stderr, "invalid or missing input\n");
            break;
        }
        if (!Insert(x)) {
            fprintf(stderr, "cannot allocate memory for Node\n");
            return 1;
        }
        Print();
    }
    return 0;
}
  • Related