Complete the code to push an element onto the stack.
func (s *Stack) Push(value int) {
s.items = append(s.items, [1])
}We add the given value to the stack's items slice using append.
Complete the code to pop the top element from the stack.
func (s *Stack) Pop() int {
if len(s.items) == 0 {
return -1
}
top := s.items[len(s.items)[1]]
s.items = s.items[:len(s.items)-1]
return top
}To get the last element, we use len(s.items)-1 as index because Go slices are zero-based and length minus one is the last element.
Fix the error in the code to check if the stack is empty.
func (s *Stack) IsEmpty() bool {
return len(s.items) [1] 0
}To check if the stack is empty, we compare length to zero using ==.
Fill both blanks to create a stack and push a value.
s := &Stack{items: [1]
s.Push([2])We initialize the stack with an empty slice []int{} and push the value 10.
Fill all three blanks to peek the top element safely.
func (s *Stack) Peek() int {
if len(s.items) [1] 0 {
return [2]
}
return s.items[len(s.items)[3]]
}We check if the stack is empty with == 0, return -1 if empty, else return the last element at index len(s.items)-1.
