'C++ Doubly linked list - deleting element from the tail using pop_back()
My pop_back() function is supposed to remove the last element in a doubly linked list. However, my current code removes the last two elements rather than just one. I have set up my pop_front() function similar to this one, which works just fine. I am having trouble figuring out what I've done wrong.
Here is part of my linkedlist header with struct Node:
class linkedlist
{
private:
struct Node{
Node* next;
Node* prev;
element_type data;
};
Node* head;
Node* tail;
unsigned int numElements;
My pop_back() function from the public section of linkedlist:
void linkedlist::pop_back()
{
if (empty())
return;
else {
Node *delBack = tail;
Node *nodeToDelete = delBack;
delBack = delBack->prev;
delBack->next = NULL;
delete nodeToDelete;
tail = delBack;
numElements--;
}
}
If the problem is not immediately obvious, then it's possible the error is buried somewhere else in the code. Still searching.
Solution 1:[1]
Though the function does not delete two nodes simultaneously nevertheless the function is wrong. It does not check whether tail->prev is equal to nullptr and it does not set head to nullptr when the list becomes empty. The function can look the following way.
void linkedlist::pop_back()
{
if ( tail )
{
Node *nodeToDelete = tail;
tail = tail->prev;
if ( tail )
{
tail->next = nullptr;
}
else
{
head = nullptr;
}
delete nodeToDelete;
numElements--;
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Vlad from Moscow |
