#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.
I refactored the code and it's worked.
The infinite loop was due to the first node pointing to the head and the head pointing to the first node.
temp->next = head;
head = temp;
So when you call Print()
the while(temp != NULL)
condition never fails.
struct Node{
int data;
struct Node* next;
};
struct Node* head;
void Insert(int x){
struct Node* temp = malloc(sizeof(struct Node));
if (temp==NULL) { printf("No available space on heap\n"); exit(1); }
temp->data = x;
temp->next = NULL;
//check if we have to insert at begining(initial node) or empty list
if (head==NULL){
head=temp;
return ;
}
//traverse till the last node to insert new node
//should not modify the head
struct Node *t=head;
while(t->next != NULL) t=t->next;
t->next= temp;
}
void Print(){
struct Node* temp = head;
printf("List is: ");
while(temp != NULL){
printf("%d", temp->data);
temp = temp->next;
}
printf("\n");
}
void destroy_mem(struct Node *head)
{//we need destroy the used memory on heap for further use
struct Node *curr = NULL;
while ((curr = head) != NULL)
{ // set curr to head, stop if list empty.
head = head->next; // moving head to next element.
free(curr); // delete saved pointer.
}
head = NULL;
}
int main(){
head = NULL; //empty list
printf("How many numbers?\n");
int n, i,x;
scanf("%d", &n);
for(int i=0; i < n; i++){
printf("Enter the number\n");
scanf("%d", &x);
Insert(x);
}
Print();
destroy_mem(head);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.