"strange" implementation of a simple chained list

Started by
2 comments, last by CoB_ChrizZz 12 years, 2 months ago
hello !

I just found this nice example.

http://pastebin.com/4QV5k0ev

Even though it works and i see the code in front of me i don't understand how this works.

The output is:

A::f 60
B::f 55 b2
B::f 44 b1
A::f 30
A::f 20
A::f 10


So it is the reversed order of the objects that have been created.
code line 15 is where the "magic" happens.
the list of A objects is static (so all created objects share the same list)
but every time a object is created the next pointer points to the list, which points to " this" (the just created object)...so how i understand this is
that the list-pointer is every time overwritten by the actual object coz the pointer is never incremented.
->

A::f 60




and the next strange thing is the void A::printList() function in line 23. I don't get this at all ^^

Can somebody explain me how this works ?
Advertisement
The "magic" is nothing more than appending the list so far to the newly created node, and storing the newly created ode as the new list's head. So in effect the new node is prepended to the list, what is also the reason why the order of nodes is reverse when the list is iterated the forward way. The order of execution of "next = list" on the one hand and "list = this" on the other is of course important here.

Example:

1. Initial situation
A::list = NULL (statically initialized)

2. 1st node creation and initialization
A::list = NULL
a1(10)
causes
a) a1.next <- A::list which is NULL, initializing a1 as the end of the list, because there is no next node available by a1.next
b) A::list <- this which is a1, so that A::list is a list with a single node now, namely a1

3. 2nd node creation and initialization
A::list = a1
a2(20)
causes
a) a2.next <- A::list which is a1, initializing a2 as node before a1
b) A::list <- this which is a2, so that A::list is a list with 2 nodes now, beginning with a2

...
list = pointer to first element.

Next parts can be rewritten like this:
this->nr = n;
this->next = first;
first = this;


Which is more in line with usual LL addition:void add(Node * n, Node ** pfirst) {
n->next = *pfirst;
*pfirst = n;
}


and the next strange thing is the void A::printList() function in line 23. I don't get this at all ^^[/quote]

Nothing strange there.
wow, thank you haeggar and Antheus. This was very helful smile.png

so:

next = list let's the next pointer still point to the las added "node" to the list and THEN the list points to the newly added object (which is the "next" of the next added node...and on and on ^^

This topic is closed to new replies.

Advertisement