tags:

views:

171

answers:

2
  void push_front(const dataType &item)
  {
     head=new dnode<dataType> (item,NULL,head);
     if (!empty())
        head->next->prev=head;
     else
        tail=head;
     numItems++;
  }

I have a piece of code here, however I don't really understand it, what is the line head->next->prev=head do ? could anyone please explain, thanks

+1  A: 

Presumably head=new dnode<dataType> (item,NULL,head); set the new head->next to the previous head, so head->next->prev=head; is fixing the prev field of said previous head (was previously NULL, is now the hew head).

Alex Martelli
+12  A: 

If the list looks like this:

      ***************
head->*Data:   XXX  *
      *Prev:   NULL *    ***************
      *Next:   --------> * Data:   YYY *
      *************** <----Prev:       *     ***************
                         * Next:   --------> * Data:   ZZZ *
                         ***************<------Prev:       *
                                             * Next:  NULL *
                                             ***************

Now: Add the new item

head = new dnode<dataType> (AAA,NULL,head);


      ***************
head->*Data:   AAA  *
      *Prev:   NULL *    ***************
      *Next:   --------> * Data:   XXX *
      ***************    * Prev:  NULL *     ***************
                         * Next:   --------> * Data:   YYY *
                         ***************<------Prev:       *     ***************
                                             * Next:   --------> * Data:   ZZZ *
                                             ***************<------Prev:       *
                                                                 * Next:  NULL *
                                                                 ***************

Notice the second item in the chain. The Prev member is still NULL.
So to add the link from the second item back to the head.

head->next->prev=head;

      ***************
head->*Data:   AAA  *
      *Prev:   NULL *    ***************
      *Next:   --------> * Data:   XXX *
      ***************<-----Prev:       *     ***************
                         * Next:   --------> * Data:   YYY *
                         ***************<------Prev:       *     ***************
                                             * Next:   --------> * Data:   ZZZ *
                                             ***************<------Prev:       *
                                                                 * Next:  NULL *
                                                                 ***************

So you can think of the line:

    head->next->prev=head;

    // This is equivelant too:

    oldHead       = head->next;
    oldHead->prev = head;
Martin York
ahh. that is so helpful, thanks guys
+1, A picture is worth a thousand words
aJ