Two Stacks Implement One Queue

Build a FIFO queue from two stacks so each element moves at most twice: push appends to the inbox stack, pop reverses it once into the outbox stack.

GoData Integrity

Code

gosnippet
51 lines
package main

import (
	"errors"
	"fmt"
)

// queue backed by two stacks: stackIn receives, stackOut reverses for pops
type queue struct {
	stackIn  []int
	stackOut []int
}

func (q *queue) push(v int) {
	q.stackIn = append(q.stackIn, v)
}

func (q *queue) pop() (int, error) {
	if len(q.stackOut) == 0 {
		if len(q.stackIn) == 0 {
			return 0, errors.New("queue is empty")
		}
		// 把入栈整批倒扣进出栈,保证先进先出
		for len(q.stackIn) > 0 {
			n := len(q.stackIn) - 1
			q.stackOut = append(q.stackOut, q.stackIn[n])
			q.stackIn = q.stackIn[:n]
		}
	}
	n := len(q.stackOut) - 1
	v := q.stackOut[n]
	q.stackOut = q.stackOut[:n]
	return v, nil
}

func main() {
	var q queue
	for _, v := range []int{1, 2, 3} {
		q.push(v)
	}
	v, _ := q.pop()
	fmt.Println("pop:", v)
	q.push(4)
	for i := 0; i < 3; i++ {
		v, _ := q.pop()
		fmt.Println("pop:", v)
	}
	if _, err := q.pop(); err != nil {
		fmt.Println("empty:", err)
	}
}

Two Stacks Implement One Queue: reading the source

Read it top to bottom: push, pop and main carry the actual work.

Repetition is confined to for len(q.stackIn) > 0 — the rest of the file is straight-line. Every fallible call checks err != nil (1 site), so an error is handled where it happens rather than bubbling invisibly.

What to watch for

  • The only requirement is the runtime itself; no packages, no install.
  • Error values are returned, not thrown — every call site must inspect err before using the other return values.

Applying it

The working definition: func (q *queue) push(v int)

Output lines are prefixed (pop:, empty:) — each printed line names the step behind it.

Start the program and main runs push and pop one after another.

Statements that matter

return 0, errors.New("queue is empty")
for _, v := range []int{1, 2, 3} {
	q.push(v)
}
func (q *queue) push(v int) {
	q.stackIn = append(q.stackIn, v)
}

Interactive Tools for This Topic

FAQ

What happens when a call fails?
The Go way: `err` comes back from each call, and 1 checkpoint here test it before proceeding.
What does Two Stacks Implement One Queue print when run?
Execute the whole file; each printed line is prefixed with a label like `pop:`, `empty:`.