有谁知道为什么我在测试 pop_back() 函数时总是出现分段错误
只有一个节点?它适用于多个节点,但在有一个节点时不起作用
节点。我在 pop_front() 函数中采用了相同的方法,它运行良好。
class linked_list{
private:
class Node{
public:
int data;
Node* next;
Node* prev;
Node(int data);
};
Node* head;
Node* tail;
int count = 0;
//--------------------------------------------------------------------------------------
public:
linked_list::linked_list(){
head = nullptr;
tail = nullptr;
}
//--------------------------------------------------------------------------------------
bool has_only_one_node(){
return (head == tail);
}
//--------------------------------------------------------------------------------------
void insert_back(int value){
Node* new_node = new Node(value);
if(is_empty()){
insert_front(value);
return;
}
else{
Node* temp = head;
while(temp->next != NULL){
temp = temp->next;
}
temp->next = new_node;
new_node->prev = temp;
new_node->next = NULL;
tail = new_node;
}
count++;
}
//--------------------------------------------------------------------------------------
void pop_front(){
if(is_empty()){
return;
}
if(has_only_one_node()){
head = nullptr;
tail = nullptr;
return;
}
Node* temp = head;
head = head->next;
if(head != nullptr) {
head->prev = nullptr;
}
delete temp;
count--;
}
//--------------------------------------------------------------------------------------
void pop_back(){
if(is_empty()){
return;
}
if(has_only_one_node()){
//delete tail;
head = nullptr;
tail = nullptr;
return;
}
Node* curr = tail;
tail = tail->prev;
if(tail != nullptr) {
tail->next = nullptr;
}
delete curr;
count--;
}
int main(int argc, const char * argv[]) {
linked_list ls;
ls.insert_back(1);
ls.pop_back();
return 0;
}
输出:分段错误。
什么错误?