- Linked list access is cheap only at the ends.
- Restrict access to linked-list ends an maybe get better (more
efficient, simpler) data structures.
- You have two choices: restrict to one end, or to both ends.
- We'll consider the one-end case here; the two-end case later.
- Four problems.
- In a card game, how do you represent the discard pile?
- The most recent card discarded should be the card that can be picked
up.
- How can I reverse a train at a terminus?
- A turntable's expensive, a loop's cheaper but inflexible
- Keeping track of function call information.
- The most recent call frame is the one that should be accessed.
- right-to-left conversion on left-to-right data.
- Converting bases is easy (right digit order) but hard (what's the
divisor) in one direction and hard (wrong digit order) but easy (the
divisor's the base) in the other direction.
- Stacks
- A
stack is a linked list in which access to the list is
restricted to one end.
- Given the data access patterns, a stacks is also known as a
last in first out queue or a
LIFO queue.
- Operations
- Make an empty stack.
- Test for an empty stack.
- Add an element to the stack (push).
- Remove an element from the stack (pop).
-
pop()
may or may not return the element removed from the stack.
- Return the value at the top of the stack (top).
- There are many other stack operations available. See the
Forth or
PostScript instruction sets for examples.
- Error states.
- You can't pop from an empty stack - stack underflow.
- Depending on implementation, you can't push into a full stack - stack
overflow.
- The four problems revisited.
- In a card game, how do you represent the discard pile?
- The discard pile can be implemented with a stack.
- How can I reverse a train at a terminus?
- A shunt can turn the train around flexibly.
- The shunt acts like a stack.
- Keeping track of function call information.
- The call frames can be stored on a stack.
- right-to-left conversion on left-to-right data.
- Convert the number from right-to-left, storing the digits in a stack.
- The two prime properties of a stack are:
- Provides access to the most recently entered value (discard piles and
call frames).
- Offers up values in reverse order (train shunt and conversion
digits).
- When you have a problem requiring either of these two properties
(access to most recent values, reversing the order of values), you
should think "stack".
This page last modified on 13 November 2003.