Search⌘ K
AI Features

Solution Review: Reverse k Element in a Stack

Explore how to reverse k elements in a stack by transferring them to a queue and back. Learn the step-by-step process and understand the time complexity in Go.

Solution

We’ll create a queue, pop k elements from the input stack, and add them to the queue. Then we’ll remove them from the queue one by one and push them back to the stack.

Coding exercise

Go (1.6.2)
package main
import "fmt"
func reverseKElementInStack(stk *Stack, k int) {
que := new(Queue)
i := 0
for (stk.Length() > 0 && i < k) {
que.Enqueue(stk.Pop())
i++
}
for (que.Length() != 0) {
stk.Push(que.Dequeue().(int))
}
}
// Testing code
func main() {
stk := new(Stack)
stk.Push(1)
stk.Push(2)
stk.Push(4)
stk.Push(3)
fmt.Print("Stack before reversal : ")
stk.Print()
reverseKElementInStack(stk, 2)
fmt.Print("Stack after reversal : ")
stk.Print()
}

Time complexity

The time complexity of the ...