next up previous index
Next: A List Node Class Up: Linked Implementations Previous: Linked Implementations   Index


The Stack as a List

The idea is to represent the stack by a list. Disregarding for the present how a list might be stored in computer memory, suppose that we begin with an empty stack corresponding to the empty list []. Now suppose we push 3 onto the stack. It will then be represented by the list [3] with just one element. If we now push 2 onto the stack, it becomes [2, 3]. Note that insertion is done at the front. A third push of 5 would give [5, 2, 3].

It is now easy to see how you pop an element off the stack. You just detach the head of the list. The first pop returns 5 leaving [2, 3]. A further pop would return 2 leaving [3]; alternatively a further push of 4 would have left the stack as [4, 2, 3].



Peter Williams 2005-06-07