虽然 运行 我的链表代码编译器在给出打印函数后也没有给出任何输出

While running my linked list code the compiler does not give any outputs after giving a print function too

我已经给出了insert和print函数,可以在链表中插入数据,然后打印出来。 但不知何故,它不提供任何输出并无限期地保持 运行 。 怎么了?

这是我写的代码。这是一个使用循环和函数创建链表的简单程序。

#include<iostream>
using namespace std;
struct node{
    int data;
    struct node* next;
};
struct node* head;

void insert(int data){
    struct node* temphead=head;
    if (temphead == NULL)
    {    
        node* temp = new node();
        temp->data=data;
        temp->next=NULL;
        while (temphead == NULL){
            head==temp;
        }
    }
    
    else if (temphead != NULL)
    {
        node* temp = new node();
        temp->data=data;
        temp->next=NULL;
        while (temphead != NULL)
        {
            temphead->next= temp;
            temphead=temphead->next;
        }
    }
}

void print(){
    struct node* tempptr = head;
    while (tempptr->next != NULL)
    {
        cout<<tempptr->data<<"_";
        tempptr=tempptr->next;
    }
    
}

int main(){
    head=NULL;

    insert(2);
    insert(4);
    insert(8);
    insert(6);
    //list - 2_4_8_6
    print();
    return 0;
}

您的代码中几乎没有错误,也没有拼写错误。请阅读标有// CHANGE HERE的评论以了解我所做的更改的描述:

#include <iostream>
using namespace std;
struct node{
    int data;
    struct node* next;
};
struct node* head;

void insert(int data){
    struct node* temphead = head;
    if (temphead == nullptr)
    {    
        node* temp = new node();
        temp->data = data;
        temp->next = nullptr;
        // CHANGE HERE: removed unnecessary while loop
        // Directly assign temp to head
        head = temp;
    }
    else
    {
        node* temp = new node();
        temp->data=data;
        temp->next=nullptr;
        // CHANGE HERE: check for temphead->next instead of temphead
        while (temphead->next != nullptr)
        {
            // CHANGE HERE: remove unnecessary line: temphead->next= temp;
            temphead=temphead->next;
        }
        // CHANGE HERE: assign temp to temphead->next (i.e. to last node)
        temphead->next = temp;
    }
}

void print(){
    struct node* tempptr = head;
    // CHANGE HERE: check for tempptr instead of tempptr->next
    while (tempptr != nullptr)
    {
        cout<<tempptr->data<<"_";
        tempptr=tempptr->next;
    }
    
}

int main(){
    head=nullptr;

    insert(2);
    insert(4);
    insert(8);
    insert(6);
    //list - 2_4_8_6
    print();
    return 0;
}

注意:您的代码使用 new 进行动态内存分配,但不会使用 delete 在不需要时取消分配内存。如果你想避免使用new/delete,你可以探索智能指针。