Back to questions
JuniorTheoryCommon
What does the program print?
package main
import "fmt"
func main() {
var s []int
s = append(s, 1, 2, 3)
a := s[len(s)-1]
s = s[:len(s)-1]
b := s[len(s)-1]
fmt.Println(a, b)
}3 2
- Expecting
1 2: a stack takes from the end it pushed to, so the last appended3comes out first, then2. - Expecting
3 3:s = s[:len(s)-1]shortenssby one element, so the nexts[len(s)-1]is2.
- What happens if you pop from an empty slice this way?
- How would you turn this stack into a queue?