Stacks Flashcards
What is a stack?
A stack is a first in, last out (FILO) abstract data structure where items are added and removed from the top.
What are the key operations in a stack?
Push (adding an item), Pop (removing the top item), and Peek (returning the value of the top item without removing it).
What does the push operation do in a stack?
It adds an item to the top of the stack if there is space.
What does the pop operation do in a stack?
It removes the top item from the stack, decreasing the stack’s size.
What is stack overflow?
Overflow happens when trying to push to a full stack.
What is stack underflow?
Underflow happens when trying to pop from an empty stack.
How is a stack used in managing function calls?
A stack stores return addresses and local variables when a function is called. When the function ends, these are popped to return to the previous state.
What is the pseudo-code for pushing an item onto an array-based stack?
if top < stack_size
then
top = top + 1
stack[top] = item
else
output “Stack Overflow Error”
end if
What is the pseudo-code for popping an item from an array-based stack?
if top <> 0
then
item = stack[top]
top = top - 1
else
output “Stack Underflow Error”
end if
What does the Peek operation do in a stack?
Returns the value of the item at the top of the stack without removing it.
Where are stacks seen in real life?
- Undo/Redo functions
- Browser history
What are some pros of using a stack?
- Simplicity
- Minimal operations
- Memory efficient
- Natural fit for specific problems
What are some cons of using a stack?
- Limited functionality
- Overflow/Underflow
- Recursive nature
- Not always optimal
What are some uses of a stack?
- Expression evaluation
- Backtracking
- Tree and Graph traversals
- Call stack management