4.2 - Stacks Flashcards
What are Stacks and how do they work?
Stacks are an example of an abstract data structure.
They work using a “First In, Last Out” (FILO) system. Think a stack of books, the first book in the stack will be the last removed.
Stacks are based on arrays similar to queues, but have just one pointer: a top pointer.
What functions can be used on stacks?
Push() - Adds an item to the stack
Pop() - Removed the item at the top of the stack
Peek() - Returns the value of the item at the top of the stack without removing it
IsFull() - Check if full
IsEmpty() - Check if empty
How would a stack work logically?
Assume we have a stack containing three names.
[]
[]
Bruce - TOP
Diego
Mary
If we apply the operation Stack.Push(“Charlie”), the stack would now look like this.
[]
Charlie - TOP
Bruce
Diego
Mary
If we used Stack.Pop, the stack would now remove Charlie and return the stack back to its previous position, with Bruce at the top.
If we now do Stack.Push(“Maria”):
Maria - TOP
Charlie
Bruce
Diego
Mary
How does a stack overflow error occur?
Maria - TOP
Charlie
Bruce
Diego
Mary
If we attempted to do Stack.Push() on this stack, a stack overflow error would occur as there are no available spaces on the stack as indicated by the top pointer.
How does a stack under flow error occur?
[]
[]
[]
[]
[] - TOP
If we attempted to do Stack.Pop() on this stack, a stack under flow error would occur as there are no items in the stack to remove.