我正在尝试编写一个简单的程序来将整数值存储在 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/