繁体   English   中英

为什么我的链表程序会无限地打印出我输入的那个“第一个数字”的循环?

[英]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();
    }

我从编译器得到的错误 output 示例:

多少个数字?

我的输入:2

输入号码:

我的输入:1

列表是: 111111111111111111111111111111111111111111111111111111111111111111111111111111111111 并且它继续 & on & on

我什至没有机会输入第二个数字,因为我输入了 2 个数字作为数字的数量。

我重构了代码并且它有效。

无限循环是由于第一个节点指向头部,而头部指向第一个节点。

temp->next = head;
head = temp;

因此,当您调用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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM