#include<stdlib.h>
#include<stdio.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 = head;
head = temp;
if(head != NULL)
temp->next = head;
head = temp;
}
void Print(){
struct Node* temp = head;
printf("List is: ");
while(temp != NULL){
printf("%d", temp->data);
temp = temp->next;
}
printf("\n");
}
int main(){
head = NULL; //empty list
printf("How many numbers?\n");
int n, i;
scanf("%d", &n);
for(int i=0; i < n; i++){
printf("Enter the number\n");
scanf("%d", &x);
Insert(x);
Print();
}
Example of the wrong output that I got from my compiler:
How many numbers?
My input: 2
Enter the number:
My input: 1
List is: 1111111111111111111111111111111111111111111111111111111111111111111111111111111111111 and it goes on & on & on
I didn't even have the chance to enter the 2nd number, since I put 2 numbers as the amount of numbers.