c++ - (核心转储)C++ 中的链表

标签 c++ linked-list coredump

我正在尝试编写一个简单的程序来将整数值存储在 3 节点链表中,但在我插入第一个值后它显示“段错误(核心已转储)”。

我对 C++ 比较陌生,所以我真的不知道自己做错了什么。我曾尝试在 Internet 上研究解决方案,但似乎找不到任何解决方案。

#include<iostream>
using namespace std;
struct node{
   int num;
   node *next;
};
node *head=NULL;
node *tail=NULL; 
void create(int num){
   node *temp=new node;
   temp->num=num;
   temp->next=NULL;
   if(head=NULL){
      head=temp;
      tail=temp;
      temp=NULL;
   }
   else{
      tail->next=temp;
      tail=temp;
   }
}

void display(node *current ){
    while(current!=NULL){
         cout<<current->num<<endl;
         current=current->next;
    }
}

int main(){

   int num;
   for(int i=0;i<3;i++){
       cout<<"Enter a number:";
       cin>>num;

   }
   display(head);
   return 0;
 }

感谢任何帮助和/或提示:)

编辑:好的,所以我看到我错过了 int he if 子句 head 应该是 head==NULL,但现在它不在末尾显示链表 :(

最佳答案

在 if 语句中将 head=NULL 更改为 head==NULL。并请在 for 循环中调用 create 函数。这是我的解决方案:

#include<iostream>
using namespace std;
struct node {
    int num;
    node *next;
};
node *head = NULL;
node *tail = NULL;
void create(int num) {
    node *temp = new node;
    temp->num = num;
    temp->next = NULL;
    if (head == NULL) {
        head = temp;
        tail = temp;
        temp = NULL;
    }
    else {
        tail->next = temp;
        tail = temp;
    }
}

void display(node *current) {
    while (current != NULL) {
        cout << current->num << endl;
        current = current->next;
    }
}

int main() {

    int num;
    for (int i = 0; i < 3; i++) {
        cout << "Enter a number:";
        cin >> num;
        create(num);
    }
    display(head);
    return 0;
}

关于c++ - (核心转储)C++ 中的链表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54518525/

相关文章:

c++ - 在 C++ 中创建节点的不同方式感到困惑?

c - 在c中递归搜索链表

gdb - 如何调试在 dlopen()'ed 插件中中止的核心转储?

c++ - 格罗马克 : Illegal instruction (core dumped)

c++ - 如何在cmake中动态设置目标库?

c++ - Visual Studio C++ 编译器选项 : Why does/O2 define/Gs?

java - 在恒定时间内将节点插入链表?

python - 在 virtualenv 中使用 python3.5 导入 torch 时出现段错误(核心转储)

c++ - 通过指针调用函数

c++ - ffmpeg 仅发布播放列表,但不发布 HLS 片段