[英]Why does my linked-list program print out a loop of that "first number" I entered, infinitely?
#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:我从编译器得到的错误 output 示例:
How many numbers?多少个数字?
My input: 2我的输入:2
Enter the number:输入号码:
My input: 1我的输入:1
List is: 1111111111111111111111111111111111111111111111111111111111111111111111111111111111111 and it goes on & on & on列表是: 111111111111111111111111111111111111111111111111111111111111111111111111111111111111 并且它继续 & on & on
I didn't even have the chance to enter the 2nd number, since I put 2 numbers as the amount of numbers.我什至没有机会输入第二个数字,因为我输入了 2 个数字作为数字的数量。
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.因此,当您调用Print()
时, while(temp != NULL)
条件永远不会失败。
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);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.