I have this code for pushing an object onto the stack, I am having trouble with understanding what each line does, if someone could explain why the previous node (newNode.next) has to be equal to top, and why then making top equal to the newNode.
void push(AnyClass newbObj)
{
Node newNode = Node(newObj);
newNode.next = top;
top = newNode;
}
This looks like a linked list implementation. In a linked list each item has a pointer (reference) to the next one in the list.
The variable
topseems to be a reference to the node at the beginning of the list and therefore represents the top of the stack.Let’s assume then that the list starts looking like this:
The first line is just casting the parameter to the right type, we could instead have defined
push()to take aNodeinstead and remove this line altogether.Since we want to insert the new node at the front, firstly we need to ensure it points to the rest of the list using:
This gives us something that looks like this
But
topis still pointing to the old item, so we now update that:Now the list looks like this:
And we’re done.