Complete the code to initialize a new queue for the stack.
type Stack struct {
queue []int
}
func NewStack() *Stack {
return &Stack{queue: [1]
}We use make([]int, 0) to create an empty slice to represent the queue.
Complete the code to push an element onto the stack using the queue.
func (s *Stack) Push(x int) {
s.queue = append(s.queue, x)
for i := 0; i < [1]; i++ {
s.queue = append(s.queue, s.queue[0])
s.queue = s.queue[1:]
}
}We rotate the queue len(s.queue) - 1 times to move the newly added element to the front.
Fix the error in the Pop method to correctly remove and return the top element.
func (s *Stack) Pop() int {
if len(s.queue) == 0 {
return -1
}
top := s.queue[[1]]
s.queue = s.queue[1:]
return top
}The top element is always at the front of the queue (index 0) after rotation in Push.
Fill both blanks to implement the Top method that returns the top element without removing it.
func (s *Stack) Top() int {
if len(s.queue) == 0 {
return -1
}
return s.queue[[1]] // top element
}The top element is at index 0 because of the rotation done in Push.
Fill all three blanks to implement the IsEmpty method that checks if the stack is empty.
func (s *Stack) IsEmpty() bool {
return [1] == [2]
}
// Usage example:
// stack := NewStack()
// empty := stack.IsEmpty() // returns [3] when stack is emptyStack is empty when the length of the queue is zero, so len(s.queue) == 0 returns true.
