Stacks 01
Stacks 01
Stack
• A stack is a last in, first out (LIFO) data
structure
– Items are removed from a stack in the reverse
order from the way they were inserted
Stack
• With a stack, we always remove the item that
was most recently inserted. This policy is known
as last-in first-out or LIFO.
• A common example of a stack is surfing the
Web. When you click a hyperlink, your browser
displays the new page (insert). You can keep
clicking on hyperlinks to visit new pages. You
can always revisit the previous page by clicking
the Back button (remove).
Stack
This algorithm returns true if there is exactly one element on the stack.
The code uses the abstract data type stack.
top = 3 or count = 4
top = 2 or count = 3
top = 6 or count = 4
• Sometimes this is done to allow two stacks to
share the same storage area
0 1 2 3 4 5 6 7 8 9
stks: 49 57 3 44 97 23 17
topStk1 = 2 topStk2 = 6
Error checking
• There are two stack errors that can occur:
– Underflow: trying to pop (or peek at) an empty stack
– Overflow: trying to push onto an already full stack
• For underflow, you should throw an exception
– If you don’t catch it yourself, Java will throw an
ArrayIndexOutOfBounds exception
– You could create your own, more informative
exception
• For overflow, you could do the same things
– Or, you could check for the problem, and copy
everything into a new, larger array