Stacks and Queues
Queue from Two Stacks
Implement queue behavior with an input stack and an output stack.
Algorithm
Basic Implementation
basic.go
package main
import (
"fmt"
"strings"
)
func render(values []int) string {
parts := make([]string, 0, len(values))
for _, value := range values {
parts = append(parts, fmt.Sprint(value))
}
return strings.Join(parts, " -> ")
}
func main() {
inStack := []int{}
outStack := []int{}
for _, value := range []int{10, 20, 30} { inStack = append(inStack, value) }
for len(inStack) > 0 { outStack = append(outStack, inStack[len(inStack)-1]); inStack = inStack[:len(inStack)-1] }
removed := []int{}
for len(outStack) > 0 { removed = append(removed, outStack[len(outStack)-1]); outStack = outStack[:len(outStack)-1] }
fmt.Println(render(removed))
}
Complexity
- Time: O(1) amortized per operation
- Space: O(n)
Implementation notes
- Go represents both stacks as
[]intslices:inStack := []int{}receives enqueues andoutStack := []int{}supplies dequeues. - Enqueue uses
append(inStack, value)for10,20, and30;appendmay grow the backing array, while the replay-visible state becomesinStack=[10, 20, 30]. - The transfer loop pops from the end with
inStack[len(inStack)-1], appends that value tooutStack, and shrinks the input slice withinStack = inStack[:len(inStack)-1], producingoutStack=[30, 20, 10]. - The dequeue loop uses the same end-pop pattern on
outStack, appending values toremovedas[10, 20, 30]. Thelen(...) > 0guards prevent empty-slice indexing. - Reslicing changes slice headers and can keep backing arrays alive while a slice is retained; this small replay drains both stack slices immediately.
renderconverts the removedintvalues withfmt.Sprint, joins them withstrings.Join(parts, " -> "), andfmt.Printlnprints10 -> 20 -> 30.
input stack
Enqueue pushes new values onto the input stack.
output stack
When the output stack is empty, transferring all input values reverses them into dequeue order.