Home > Net >  Why is my program only printing the headnode and the last node? Are the other numbers stored in the
Why is my program only printing the headnode and the last node? Are the other numbers stored in the

Time:08-22

I created a linked list function which return a pointer to the node. Then I iterated n amount times to accept the number from the user and store it in a linked list, connecting all the nodes. But it is only printing the first and last node. See my code below:

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

typedef struct node {
    int number;
    struct node *next;
} nd;

nd* create(int num);

int main(void) {
    int n;
    printf("How many numbers do you intend on entering ");
    scanf("%d", &n);
    int num;
    nd* bg = NULL;

    for (int i = 0; i < n; i  ) {
        printf("Enter a number");
        scanf("%d", &num);
        nd *ls = malloc(sizeof(nd));
        ls = create(num);
    
        if (i == 0) {
            bg = ls;
        }
        else {
            nd *p = malloc(sizeof(nd));
            p = bg;
            p->next = ls;
        }
    }

    for (nd *k = bg; k != NULL; k = k->next) {
        printf("%d\n", k->number);
    }
}

nd* create(int num) {
    nd *list = malloc(sizeof(nd));

    if (list == NULL) { // Check to if we have ran out of memory
        return 0;
    }

    list->number = num;
    list->next = NULL;

    return list;
}

CodePudding user response:

First thing I notice: create allocates memory for a new node. So why allocate memory before that for the same pointer?

        nd *ls = malloc(sizeof(nd));
        ls = create(num);

The results of this first malloc, if it succeeded, are now unable to be freed as we do not have a pointer to it.

Within your loop, you have created a node ls and then another p.

Slow down and think through what you're doing. In your loop:

  • You prompt for a number.
  • Create a node with that data.
  • If your head node bg is NULL you have bg point to that node.
  • Otherwise you link that node to the previous node.
int main(void) {
    int n;
    printf("How many numbers do you intend on entering ");
    scanf("%d",&n);

    int num;
    nd *bg = NULL;
    nd *cur, *prev;

    for (int i = 0; i < n; i  ) {
        printf("Enter a number");
        scanf("%d",&num);
        cur = create(num);

        if (!bg) {
            bg = cur;
        }
        else {
            prev->next = cur;
        }

        prev = cur;
    }

    for (nd *k = bg; k != NULL; k = k->next) {
       printf("%d\n",k->number);
    }

    return 0;
}

You'll also want to walk your list and free all of the memory you've allocated.

  • Related