user6106197
user6106197

Reputation:

Member access in a doubly-linked list

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;


}

Upvotes: 2

Views: 259

Answers (1)

kabanus
kabanus

Reputation: 25895

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.

Upvotes: 2

Related Questions