我正在尝试实现通用的双链表。将节点添加为头的成员函数给出了分段错误(核心已转储)。我认为错误位于“ d_list.h”中add _ .. head()函数的else块中。 我不知道错误在哪里?
问题:如何在代码中查找分段错误? 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;
}
}
};
#endif
节点
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;
};
};
main.cpp
#include<iostream>
#include "d_list.h"
using namespace std;
int main(){
d_list<int> d1;
cout<<d1.gethead();
cout<<"\n";
d1.add_node_as_head(5);
cout<<d1.gethead()<<"\n";
d1.add_node_as_head(6);
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)