Here's your example, in Java syntax:
Node yourList = /* [Obj 1] <- [Obj 2] <- [Obj 3] <- [Obj 4] */;
yourList = reverse(yourList);
You start with four objects in the heap (the four nodes of your list), and one variable on the stack, yourList
. This variable holds a reference to Obj 1
's location in the heap. When reverse()
is called it is handed the reference to Obj 1
and iterates through each object, reversing the list. Finally it returns a reference to Obj 4
. The yourList
variable is then updated to reference Obj 4
. Since Obj 4
in turn references the other objects, none of them will be garbage collected.
All that happens to yourList
is its value is updated. It previously stored the location (address) of Obj 1
, now it stores the location of Obj 4
. The previous value isn't garbage collected, it's overwritten. So after reverse()
returns we end up with the same four objects on the heap, and the same one variable on the stack.