Austin
Austin

Reputation: 25

Deleting a node in a linked list C++

So I'm having a hard time getting this to work, and even after extensive googling I can't quite get it to work. Here's the function I'm working on :

bool deleteOneOf(const std::string & target)
{
    Node * ptr = _first;
    Node * temp;
    while (ptr != nullptr)
    {
        if (target != ptr->_entry)
        {
            temp = ptr;
            ptr = ptr->_link;
        }
        else
        {
            temp->_link = ptr->_link;
            delete ptr->_link;
            return true;
        }
    }
    return false;
}

The Node class I have to work with is this:

class Node
{
public:
    std::string _entry;
    Node * _link;

    Node(std::string entry, Node * link) : _entry(entry), _link(link)
    {}
};

Any help is greatly appreciated, thanks.

Upvotes: 0

Views: 64

Answers (1)

Rob L
Rob L

Reputation: 2530

You haven't initialized temp. If you are looking at the first element in the list, it will point to garbage. Also, you need to delete ptr. Fixed code:

bool deleteOneOf(const std::string & target)
{
    Node * ptr = _first;
    Node * temp = nullptr;
    while (ptr != nullptr)
    {
        if (target != ptr->_entry)
        {
            temp = ptr;
            ptr = ptr->_link;
        }
        else
        {
            if (temp)
                temp->_link = ptr->_link;
            else
                _first = ptr->_link;
            delete ptr;
            return true;
        }
    }
    return false;
}

Upvotes: 1

Related Questions