Solution Review: Reverse k Element in a Stack
Let’s discuss in detail the solution of the challenge posed in the previous lesson.
We'll cover the following...
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
Press + to interact
main.go
queue.go
stack.go
package mainimport "fmt"func reverseKElementInStack(stk *Stack, k int) {que := new(Queue)i := 0for (stk.Length() > 0 && i < k) {que.Enqueue(stk.Pop())i++}for (que.Length() != 0) {stk.Push(que.Dequeue().(int))}}// Testing codefunc 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 ...