运行链表程序时程序崩溃

时间:2021-04-13 16:08:06

标签: 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;
        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;
}

当我输入要插入的数字时,它显示程序已停止工作。我正在尝试将数字插入链表并在每次添加数字时打印它。我检查了许多其他错误,但没有。

1 个答案:

答案 0 :(得分:0)

看起来可能是由于其中一条评论所说的无限循环。尝试像这样更新 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;
    }
}
相关问题