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