简体   繁体   English

C ++链表

[英]C++ linked lists

I'm working on an assignment using a modified version of the list class. 我正在使用列表类的修改版本进行分配。

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

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

The objective I am trying to accomplish is after entering a list, I need to be able to delete one member so if i enter: 我要完成的目标是输入列表后,我需要能够删除一个成员,因此如果输入:

a
b
c
d
e

I need to be able to delete c, and leave the rest unaffected. 我需要能够删除c,并使其余部分不受影响。 My function is: 我的职能是:

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

        }

and the find function is: 查找功能是:

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

The problem I'm having is If i input C to be deleted, it doesn't correctly link B to D, so C, D, E, are all deleted rather than just C. So the output is AB, rather than ABDE as it should be. 我遇到的问题是,如果我输入要删除的C,它不能正确地将B链接到D,因此C,D,E都被删除了,而不仅仅是C。所以输出是AB,而不是ABDE它应该是。

The code in deleteOneOf() looks slightly confusing to me. deleteOneOf()中的代码对我来说有点混乱。 It's not clear to me what approach you were trying to implement, but it does not have to be this complicated. 我不清楚您要尝试采用哪种方法,但是不必那么复杂。

I'm assuming that _first is the head pointer to the list. 我假设_first是指向列表的头指针。 In that case: 在这种情况下:

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

Unless I'm missing some part of your requirement, this should be all that's needed. 除非我缺少您的要求的一部分,否则这应该是全部。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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