Imagine you are baking cookies and following a recipe step by step. Why is a stack useful when a computer runs functions that call other functions?
Think about how you remember where you left off when you pause a task and start another.
A stack helps the computer remember the order of function calls so it can return to the right place after finishing each function. This is like putting tasks on a stack and finishing the last one first.
What is the printed state of the stack after these operations?
stack := []int{} stack = append(stack, 10) // push 10 stack = append(stack, 20) // push 20 stack = stack[:len(stack)-1] // pop stack = append(stack, 30) // push 30 fmt.Println(stack)
Remember that pop removes the last pushed item.
We push 10, then 20. Popping removes 20. Then pushing 30 adds it on top. So the stack has 10 and 30.
Look at this Go code for popping from a stack. Why does it cause a runtime error?
stack := []int{} stack = append(stack, 5) stack = stack[:len(stack)-1] stack = stack[:len(stack)-1] // error here fmt.Println(stack)
Think about what happens if you remove more items than exist.
After popping once, the stack is empty. Trying to pop again reduces length below zero, causing a runtime error.
Which code snippet correctly uses a stack to reverse the string "hello"?
Think about how popping from a stack reverses order.
Option B pushes all characters, then pops them to reverse the string. Others either do not reverse or use inefficient methods.
In text editors, undo actions are often implemented using a stack. Why is a stack the best choice for this?
Think about which action you want to undo first.
Undoing requires reversing the order of actions. The last action done should be undone first, which fits the stack's last-in, first-out rule.
