C++ linked lists

C++ linked lists

本文关键字:lists linked C++      更新时间:2023-10-16

我正在使用list类的修改版本进行作业。

class List
{
private:
    class Node
    {
    public:
        std::string _entry;
        Node * _link;
        Node(std::string entry, Node * link) : _entry(entry), _link(link)
        {}
    };
};

我想要完成的目标是进入一个列表后,我需要能够删除一个成员,所以如果我输入:

a
b
c
d
e

我需要能够删除c,而不影响其余部分。我的功能是:

    bool deleteOneOf(const std::string & target)
        {
            Node * & del = _first;
            Node *  temp = _first;
            if (contains(target))
            { 
               del = find(temp, target);
               del = del->_link;
            }
                delete temp;
                return true;
            }
            else
            {
                return false;
            }
        }

, find函数为:

Node * & find(Node * & ptr, const std::string & target)
    {
        if (ptr == nullptr || ptr->_entry == target)
        {
            return ptr;
        }
        else
        {
            return find(ptr->_link, target);
        }
    }

我遇到的问题是,如果我输入C要删除,它不能正确地将B链接到D,所以C, D, E都被删除了,而不仅仅是C。所以输出是A B,而不是应该的A B D E。

deleteOneOf()中的代码对我来说有点混乱。我不清楚你想采用什么方法,但没必要这么复杂。

我假设_first是指向列表的头指针。在这种情况下:

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

除非我遗漏了您的某些要求,否则这应该是所有需要的。