C++ 程序在运行链表程序时崩溃

C++ 程序在运行链表程序时崩溃,c++,linked-list,C++,Linked List,这是密码 #include <iostream> using namespace std; struct Node{ int data; Node *next; }; Node *head; `insert function takes a number as argument` void insert(int a) { Node *temp = new Node(); temp -> data= a;

这是密码

#include <iostream>

using namespace std;

struct Node{
        int data;
        Node *next;
};
Node *head;

`insert function takes a number as argument`
void insert(int a)
{
        Node *temp = new Node();
        temp -> data= a;
        temp->next = head;
        head = temp;

}

void print(void)
{
        Node *temp1;
        temp1 = head;
        while(head != NULL)
  {

      cout<<temp1->data<<endl;
      temp1 = temp1->next;

  }
}
**main function**
int main()
{
        head = NULL;
        int a;
        int b;
        cout<<"how many elements do you want to insert";
        cin>>b;
        for (int i = 0;i < b; i++)
    {
         cout<<"enter a number"<<endl;
         cin>>a;
         insert(a);
         print();
    }
        return 0;
}
#包括
使用名称空间std;
结构节点{
int数据;
节点*下一步;
};
节点*头;
`insert函数将数字作为参数`
空白插入(INTA)
{
Node*temp=新节点();
温度->数据=a;
温度->下一步=头部;
压头=温度;
}
作废打印(作废)
{
节点*temp1;
temp1=头部;
while(head!=NULL)
{

cout看起来可能是由于一个无限循环造成的,如其中一条注释所述。请尝试在
print
函数中更新循环,如下所示:

void print() {
    Node *temp1;
    temp1 = head;

    // Here, I switched `head` with `temp1`
    while (temp1 != nullptr) {
        std::cout << temp1->data << std::endl;
        temp1 = temp1->next;
    }
}
void print(){
节点*temp1;
temp1=头部;
//这里,我把head换成temp1`
while(temp1!=nullptr){
std::cout数据下一步;
}
}

while(head!=NULL)
永远不会结束。您可以通过使用调试器单步执行代码来轻松找到它。无关:
insert
函数可以是一行。
head=新节点{a,head}我不喜欢在C++下看到C样式链表。制作一个实际的模板类,为它编写迭代器。在C++中编写一个正确的链表是一个很好的方法来执行各种各样的C++原理和实践。这是忙碌的工作。无关的:你应该有一个守则在<代码> CIN > a;< /代码>。如果某些傻瓜键入的字母或其他内容不是
int
的有效部分,例如
if(cin>>a){insert(a);}else{cin.clear();cin.ignore(numeric_limits::max(),'\n');i-->
可以工作,但最好更改循环类型A并使其迭代,直到有效输入的计数达到
b