打印链表元素时C++出现分段错误



请提供帮助。当我尝试打印这个链表中的元素时,我遇到了分段错误。我首先声明一个类,插入和显示列表元素的函数就是它的函数。代码:

#include <iostream>
using namespace std;
struct node{
int data;
node *next;
};
class ll{
node *head,*tail;
public:
void push(int x){
node *temp = new node;
temp->data = x;
temp->next = NULL;
if(head == NULL){
head = temp;
tail= temp;
}
else{
tail->next = temp;
tail= temp;
}
}
void show(){
node *n = head;
while(n!=NULL){
cout<<n->data<<"n";
n = n->next;
}
}
};
int main()
{
ll a;
a.push(1);
a.push(2);
a.show();
return 0;
}

数据成员头和数据成员尾都不是由nullptr初始化的。所以程序有未定义的行为。

你可以在类定义中写

class ll{
node *head = nullptr, *tail = nullptr;
//...

请记住,结构节点应该是类ll的成员。例如

class ll{
struct node{
int data;
node *next;
} *head = nullptr,*tail = nullptr;
public:
void push( int x ){
node *temp = new node { x, nullptr };
if( head == NULL ){
head = tail = temp;
}
else {
tail = tail->next = temp;
}
}
//...

您可以在默认构造函数中初始化它们,而不是在类定义中初始化数据成员,例如

class ll{
struct node{
int data;
node *next;
} *head,*tail;
public:
ll() : head( nullptr ), tail( nullptr ) {}
// ...

此外,您至少需要定义析构函数,并显式定义复制构造函数和复制赋值构造函数,或者将它们定义为已删除。例如

class ll{
struct node{
int data;
node *next;
} *head,*tail;
public:
ll() : head( nullptr ), tail( nullptr ) {}
~ll() { /* must be defined */ }
ll( const LL & ) = delete;
ll & operator =( const ll & ) = delete;
// ...

问题是在创建列表时没有将head设置为NULL。同样的问题也适用于tail。这是构造函数的工作

class ll {
node *head,*tail;
public:
ll() { head = tail = NULL; }
void push(int x) {
...

最新更新