Complete the code to push an element onto the stack using array direct use.
stack := []int{1, 2, 3}
stack = append(stack, [1])
fmt.Println(stack)To add an element to the stack (array), we use append with the new value, here 4.
Complete the code to pop the top element from the stack using array direct use.
stack := []int{1, 2, 3, 4}
top := stack[len(stack)[1]]
stack = stack[:len(stack)-1]
fmt.Println(top, stack)To get the last element, we use len(stack)-1 as index because slices are zero-based.
Fix the error in the stack pop function that uses array direct use.
func pop(stack []int) ([]int, int) {
if len(stack) == 0 {
return stack, 0
}
top := stack[len(stack)[1]]
stack = stack[:len(stack)-1]
return stack, top
}The last element index is len(stack)-1, so use -1 to get the top element.
Fill both blanks to implement a stack push method using struct abstraction.
type Stack struct {
items []int
}
func (s *Stack) Push([1] int) {
s.items = append(s.items, [2])
}The method takes a parameter named 'value' and appends it to the items slice.
Fill all three blanks to implement a stack pop method using struct abstraction.
func (s *Stack) Pop() (int, bool) {
if len(s.items) == 0 {
return 0, false
}
top := s.items[len(s.items)[1]]
s.items = s.items[:len(s.items)[2]]
return top, [3]
}Use len(s.items)-1 to get last element and slice to remove it. Return true to indicate success.
