Member access in a doubly-linked list

拥有回忆 提交于 2019-12-10 23:30:56

问题


I'm currently at chapter 17 of Programming: Principles and Practice using C++ and I can't figure something out. In the code below, what does the line norse_gods->succ->prev = norse_gods actually do? I know that -> is a member access operator, given a pointer to an object. Does it mean that I'm accessing norse_gods successors predecessor? I'm kind of confused with that. This is only the first part, later on in the book an insert operation is defined, which uses the same notation so I'd like to know exactly what it means. Thank you for your time.

Here is the code:

struct Link {
string value;
Link* prev;
Link* succ;
Link(const string& v, Link* p = nullptr, Link* s = nullptr)
    : value(v), prev(p), succ(s) {}
};

//insert n before p (incomplete)
Link* insert(Link* p, Link*n)
{
    n->succ = p;
    p->prev->succ = n;
    n->prev = p->prev;
    p->prev = n;
    return n;
}

int main()
{
    //Building a list of Norse gods
    //                            val      prev     suc
    Link* norse_gods = new Link{ "Thor", nullptr, nullptr };
    norse_gods =       new Link{ "Odin", nullptr, norse_gods };

    norse_gods->succ->prev = norse_gods;
    norse_gods =       new Link{ "Freya", nullptr, norse_gods };

    norse_gods->succ->prev = norse_gods;


}

回答1:


This:

Link* norse_gods = new Link{ "Thor", nullptr, nullptr };

Created a node with a NULL successor and predecessor. Now we attach a second node at the beginning:

norse_gods =       new Link{ "Odin", nullptr, norse_gods };

Note the previous node in norse_gods, Thor, is attached as a successor. So now we have

Odin -> Thor

But Thor's predecessor pointer is still NULL! We didn't touch it! But we know now it's Odin. So let's fix it to point to Odin, which is currently pointed to by norse_gods:

norse_gods->successor /*Translates to Odin's successor, which is Thor*/ ->predecessor /*This is still null from the first line*/ = /*So fix it to point to the current norse_gods, Odin*/ = norse_gods /*pointing to Odin*/

So now the link is fixed, and Thor's predecessor is Odin, as it should be.



来源:https://stackoverflow.com/questions/44589999/member-access-in-a-doubly-linked-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!