分段错误通用双链表



我正在尝试实现一个通用的双链表。添加节点作为头部的成员函数给出分段错误(核心转储(。我认为错误在于add_中的其他块中的某个地方。head(( 函数在 "d_list.h" 中。 我无法弄清楚错误在哪里?

问:如何查找代码中的分段错误?

d_list.h

#ifndef NODE_H
#define NODE_H


#include<iostream>
#include "node.h"
template<class T>
class d_list{
private:
int l_size;
Node<T>* head;
Node<T>* tail;

public:
//default constructor
d_list(){
head=nullptr;
tail=nullptr;
}

Node<T>* gethead(){return head;}
Node<T>* gettail(){return tail;}

int get_list_size(){
return this->l_size;
}

void add_node_as_head(T data){
Node<T>* current_node= new Node<T>(data);
if(this->head=nullptr){

this->head=current_node;
this->tail=current_node;
current_node->next=nullptr;
current_node->previous=nullptr;
this->l_size=l_size+1;

}else if(this->head!=nullptr){

this->head->previous=current_node;

current_node->previous=nullptr;
this->head=current_node;
this->l_size=l_size+1;

}
}
void removefromfront(){
Node<T>* temp = this->head;
this->head=this->head->next;

this->l_size= l_size-1;
}
};

#endif

节点.h

template<class T>
class Node{
private:

T data;
public:
Node<T>* previous;
Node<T>* next;
Node()=default;
Node(T m_data){
data=m_data;
previous=nullptr;
next=nullptr;
};

};

主.cpp

#include<iostream>
#include "d_list.h"
using namespace std;
int main(){
d_list<int> d1;
cout<<d1.gethead()<<"Head Initially";
cout<<"n";
d1.add_node_as_head(5);
cout<<d1.gethead()<<"Head after adding 1st elementn";
cout<<d1.gettail()<<"Tail after adding 1st elementn";
d1.add_node_as_head(6);
cout<<d1.gethead()<<"Head after adding 2nd elementn";
cout<<d1.gettail()<<"Tail after adding 2nd elementn";

d1.add_node_as_tail(7);
cout<<d1.gethead()<<"Head after adding element as Tailn";
cout<<d1.gettail()<<"Tail after adding element as Tailn";
cout<<d1.get_list_size()<<"Size after adding three elementsn";
d1.removefromfront();
cout<<d1.gethead()<<"Head After Removing from frontn";
cout<<d1.gettail()<<"Tail After Removing from front n";
cout<<d1.get_list_size()<<"n";
return 0;
}

我试过 gdb 无法修复它!

Thread 1 received signal SIGSEGV, Segmentation fault.
0x000000000041598e in d_list<int>::add_node_as_head (this=0x7bfe30, data=5) at d_list.h:40
40      nullptr){
(gdb)

在add_node_as_head函数中,您正在使用赋值运算符(this->head = nullptr(。

相反,您应该使用等于运算符(this->head == nullptr(。

相关内容

  • 没有找到相关文章

最新更新