Concept Flow - Peek Top Element of Stack
Start
Check if stack is empty?
Yes→Return error or nil
No
Access top element
Return top element
End
The flow checks if the stack is empty, if not, it accesses and returns the top element without removing it.
package main import "fmt" func main() { stack := []int{10, 20, 30} top := stack[len(stack)-1] fmt.Println(top) }
| Step | Operation | Stack State | Pointer Changes | Visual State |
|---|---|---|---|---|
| 1 | Start with stack initialized | [10, 20, 30] | top pointer not set | 10 -> 20 -> 30 -> null |
| 2 | Check if stack is empty | [10, 20, 30] | No change | 10 -> 20 -> 30 -> null |
| 3 | Access top element at index len(stack)-1 | [10, 20, 30] | top = 30 | 10 -> 20 -> 30 -> null (top points here) |
| 4 | Return top element | [10, 20, 30] | No change | 10 -> 20 -> 30 -> null (top points here) |
| 5 | End | [10, 20, 30] | No change | 10 -> 20 -> 30 -> null (top points here) |
| Variable | Start | After Step 2 | After Step 3 | Final |
|---|---|---|---|---|
| stack | [10, 20, 30] | [10, 20, 30] | [10, 20, 30] | [10, 20, 30] |
| top | undefined | undefined | 30 | 30 |
Peek Top Element of Stack: - Check if stack is empty - If empty, return error or nil - Else, access element at index len(stack)-1 - Return this element without removing - Stack remains unchanged
peek operation do in a stack?stack?stack := []int{10, 20, 30}
top := stack[len(stack)-1]
fmt.Println(top)stack := []int{}
top := stack[len(stack)-1]
fmt.Println(top)stack := []int{5, 10, 15}, write the correct Go code snippet to safely peek the top element and handle the case when the stack is empty.Pass the test and this pattern moves unknown