简体   繁体   中英

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.

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM