Level: BeginnerGo Programs

Go Stack and Queue Programs: Brackets, Min Stack, Ring Queue

Updated 21 min read
Go Stack and Queue Programs featured image: brackets, min stack and queue output

Go stack and queue programs show up in almost every coding interview, from “check the brackets” to “find the next greater number”. In this post, you will write fourteen programs with their exact output and the logic explained in comments, covering a slice stack, valid parentheses, a min stack, postfix maths, a circular queue and a sliding window.

You should first finish our Go slice programs and Go linked list programs, because a stack and a queue are built on top of them. The Go struct programs help with the methods. All programs were tested on Go 1.27.

What are Go Stack and Queue Programs?

Go stack and queue programs store items and take them out in a fixed order. A stack is LIFO, which means last in, first out. A queue is FIFO, which means first in, first out.

Think of a pile of plates. You put a clean plate on top and take the top one off first, so that is a stack. A line at a ticket counter is a queue, because the person who came first is served first.

Why Go Stack and Queue Programs Matter

These two structures solve a surprising number of real problems.

  • Undo and back buttons: editors and browsers keep a stack of past actions.
  • Job processing: web servers put requests and background jobs in a queue.
  • Parsing: compilers and calculators use a stack to match brackets and evaluate maths.
  • Interviews: valid parentheses, min stack and queue with two stacks are classic questions.

How Go Stack and Queue Programs Work

Go has no built-in stack or queue type, so we use a slice. For a stack, we add and remove at the end of the slice. For a queue, we add at the end and remove from the front.

Go stack and queue programs diagram showing push and pop on a stack and enqueue and dequeue on a queue
A stack adds and removes at the top, while a queue adds at the back and removes from the front.

The table below shows the slice code for each operation.

OperationStack codeQueue code
Addstack = append(stack, value)queue = append(queue, value)
Look at nextstack[len(stack)-1]queue[0]
Removestack = stack[:len(stack)-1]queue = queue[1:]
Is emptylen(stack) == 0len(queue) == 0
OrderLast in, first outFirst in, first out

Stack Go Stack and Queue Programs

These first Go stack and queue programs build a stack and use it to solve four classic problems.

Program 1: A Simple Stack of Plates

package main

import "fmt"

func main() {
    // A pile of plates. The end of the slice is the top of the pile.
    var plates []string // an empty slice of strings

    // Step 1: push three plates on top, one by one.
    plates = append(plates, "red") // append adds an item to the end
    plates = append(plates, "green")
    plates = append(plates, "blue")
    fmt.Println("pile:", plates)

    // Step 2: look at the top plate. It is the last item.
    top := plates[len(plates)-1] // := creates a variable; len gives the item count
    fmt.Println("top:", top)

    // Step 3: pop the top plate by cutting off the last item.
    plates = plates[:len(plates)-1] // [:n] keeps the items before index n
    fmt.Println("after pop:", plates)
}
pile: [red green blue]
top: blue
after pop: [red green]

This is a stack with no extra code at all. You push with append, which adds to the end of the slice. Then you read the top with the last index, and you pop by slicing off the last item.

Program 2: A Stack Built on a Slice

package main

import "fmt"

// Stack holds whole numbers. The end of the slice is the top.
type Stack struct {
    items []int
}

// Push adds a value on top of the stack.
func (stack *Stack) Push(value int) {
    stack.items = append(stack.items, value)
}

// Pop removes and returns the top item.
// The second result (ok) is false when the stack is empty.
func (stack *Stack) Pop() (int, bool) {
    if len(stack.items) == 0 {
        return 0, false
    }
    lastIndex := len(stack.items) - 1
    top := stack.items[lastIndex]
    stack.items = stack.items[:lastIndex] // shrink by one
    return top, true
}

// Peek reads the top item without removing it.
func (stack *Stack) Peek() (int, bool) {
    if len(stack.items) == 0 {
        return 0, false
    }
    return stack.items[len(stack.items)-1], true
}

func main() {
    var stack Stack // the zero value is an empty stack
    stack.Push(10)
    stack.Push(20)
    stack.Push(30)

    top, _ := stack.Peek() // _ ignores the ok value here
    fmt.Println("peek:", top)
    for {
        value, ok := stack.Pop() // ok is true when a value came out
        if !ok {
            break // the stack is empty, so leave the loop
        }
        fmt.Print(value, " ")
    }
    fmt.Println()
}
peek: 30
30 20 10

The Stack type wraps the slice in three small methods. In Go stack and queue programs, both Push and Pop should be O(1), because they only touch the end of the slice. The ok flag makes it safe to pop from an empty stack, so the loop stops cleanly.

Program 3: Valid Parentheses

package main

import "fmt"

// isValid checks that every bracket is closed in the right order.
func isValid(text string) bool {
    // pairs maps each closing bracket to its opening bracket. A rune is one character.
    pairs := map[rune]rune{')': '(', ']': '[', '}': '{'}
    var stack []rune
    for _, char := range text { // range gives each character; _ skips its index
        switch char {
        case '(', '[', '{':
            stack = append(stack, char) // remember the open bracket
        case ')', ']', '}':
            if len(stack) == 0 {
                return false // nothing is open, so nothing can close
            }
            top := stack[len(stack)-1]
            if top != pairs[char] {
                return false // the wrong kind of bracket
            }
            stack = stack[:len(stack)-1] // matched, so pop it
        }
    }
    return len(stack) == 0 // leftover open brackets mean invalid
}

func main() {
    for _, text := range []string{"()[]{}", "{[()]}", "(]", "((", "a(b)c"} {
        fmt.Println(text, isValid(text))
    }
}
()[]{} true
{[()]} true
(] false
(( false
a(b)c true

Each open bracket goes on the stack. When a closing bracket arrives, the top of the stack must be its matching partner. The last open bracket must be the first one closed, which is exactly LIFO, and it is the most asked of all Go stack and queue programs. Other characters, like letters, are ignored.

Program 4: Min Stack in O(1)

package main

import "fmt"

// MinStack keeps a second stack holding the minimum at each level.
type MinStack struct {
    values   []int
    minimums []int
}

// Push adds a value and records the smallest value so far.
func (stack *MinStack) Push(value int) {
    stack.values = append(stack.values, value)
    if len(stack.minimums) == 0 {
        stack.minimums = append(stack.minimums, value) // the first value is the minimum
        return
    }
    currentMin := stack.minimums[len(stack.minimums)-1]
    if value < currentMin {
        stack.minimums = append(stack.minimums, value) // a new smallest value
    } else {
        stack.minimums = append(stack.minimums, currentMin) // repeat the old minimum
    }
}

// Pop removes the top value from both stacks.
func (stack *MinStack) Pop() {
    stack.values = stack.values[:len(stack.values)-1]
    stack.minimums = stack.minimums[:len(stack.minimums)-1] // both shrink together
}

// Min returns the smallest value in the stack right now.
func (stack *MinStack) Min() int {
    return stack.minimums[len(stack.minimums)-1]
}

func main() {
    var stack MinStack
    for _, value := range []int{5, 3, 7, 2} {
        stack.Push(value)
        fmt.Println("push", value, "min", stack.Min())
    }
    stack.Pop()
    fmt.Println("after pop, min", stack.Min())
}
push 5 min 5
push 3 min 3
push 7 min 3
push 2 min 2
after pop, min 3

Every push adds one item to values and one item to minimums. Each level of minimums remembers the smallest value up to that point. So after a pop, the old minimum is already waiting underneath.

Program 5: Evaluate a Postfix Expression

package main

import (
    "fmt"
    "strconv"
    "strings"
)

// calculate applies one operator to two numbers.
func calculate(left, right int, operator string) int {
    switch operator {
    case "+":
        return left + right
    case "-":
        return left - right
    case "*":
        return left * right
    default:
        return left / right // "/" is the only operator left
    }
}

// evalPostfix reads tokens left to right. Numbers go on the stack,
// and an operator pops two numbers and pushes the result.
func evalPostfix(expression string) int {
    var stack []int
    for _, token := range strings.Fields(expression) { // Fields splits the text at spaces
        if token == "+" || token == "-" || token == "*" || token == "/" {
            // Step 1: pop two numbers. The top one is the right side.
            right := stack[len(stack)-1]
            left := stack[len(stack)-2]
            stack = stack[:len(stack)-2]
            // Step 2: push the result back on the stack.
            stack = append(stack, calculate(left, right, token))
        } else {
            number, _ := strconv.Atoi(token) // Atoi turns "10" into 10; _ ignores the error
            stack = append(stack, number)
        }
    }
    return stack[0] // the final answer is the only item left
}

func main() {
    fmt.Println(evalPostfix("3 4 + 2 *"))      // (3 + 4) * 2
    fmt.Println(evalPostfix("10 2 8 * + 3 -")) // 10 + 2*8 - 3
}
14
23

In postfix, the operator comes after its two numbers. Numbers go on the stack, and each operator pops two of them and pushes the answer. The order of left and right matters for - and /. The first number pushed is left, so 10 3 - gives 7, not -7.

Program 6: Next Greater Element with a Monotonic Stack

package main

import "fmt"

// nextGreater finds, for each item, the first bigger item to its right.
// The stack holds indexes whose answer we have not found yet.
func nextGreater(numbers []int) []int {
    result := make([]int, len(numbers)) // make creates a slice of zeros, one per number
    for i := range result {
        result[i] = -1 // default when nothing bigger exists
    }
    var stack []int // indexes still waiting for a bigger number
    for i, value := range numbers {
        // Pop every waiting index whose number is smaller than value.
        for len(stack) > 0 {
            topIndex := stack[len(stack)-1]
            if numbers[topIndex] >= value {
                break // the top is not smaller, so stop popping
            }
            result[topIndex] = value // value is the answer for that index
            stack = stack[:len(stack)-1]
        }
        stack = append(stack, i) // index i now waits for its own answer
    }
    return result
}

func main() {
    fmt.Println(nextGreater([]int{4, 5, 2, 25, 7}))
}
[5 25 25 -1 -1]

Here the stack holds the indexes that still wait for a bigger number. When a bigger value arrives, it becomes the answer for every smaller index it pops. Each index is pushed once and popped at most once, so this is O(n) instead of the O(n squared) double loop. Stock span and daily temperature questions use the same idea.

Queue Go Stack and Queue Programs

These Go stack and queue programs switch to FIFO order, where the oldest item leaves first.

Program 7: A Simple Queue at a Ticket Counter

package main

import "fmt"

func main() {
    // A ticket line. The front of the slice is the front of the line.
    var line []string

    // Step 1: people join at the back (enqueue).
    line = append(line, "Asha")
    line = append(line, "Ravi")
    line = append(line, "Meera")
    fmt.Println("line:", line)

    // Step 2: serve the person at the front (dequeue).
    first := line[0] // index 0 is the front of the line
    line = line[1:]  // [1:] keeps everything after the front
    fmt.Println("served:", first)
    fmt.Println("line now:", line)
}
line: [Asha Ravi Meera]
served: Asha
line now: [Ravi Meera]

New people join at the back with append. The person at index 0 came first, so they are served first. After that, line[1:] drops the front, and the next person moves up.

Program 8: A Queue Built on a Slice

package main

import "fmt"

// Queue holds names in the order they arrived.
type Queue struct {
    items []string
}

// Enqueue adds a name at the back of the queue.
func (queue *Queue) Enqueue(name string) {
    queue.items = append(queue.items, name)
}

// Dequeue removes and returns the name at the front.
// The second result is false when the queue is empty.
func (queue *Queue) Dequeue() (string, bool) {
    if len(queue.items) == 0 {
        return "", false
    }
    front := queue.items[0]
    queue.items[0] = ""             // clear the slot so the string can be freed
    queue.items = queue.items[1:]   // move the front forward
    return front, true
}

func main() {
    var queue Queue
    for _, customer := range []string{"Asha", "Ravi", "Meera"} {
        queue.Enqueue(customer)
    }
    for {
        name, ok := queue.Dequeue() // ok is false once the queue is empty
        if !ok {
            break
        }
        fmt.Println("serving", name)
    }
}
serving Asha
serving Ravi
serving Meera

This wraps Program 7 in a type with two methods. queue.items[1:] is O(1), but the old front slots stay in memory until append copies to a new array. Clearing the slot first lets the garbage collector free large values.

Program 9: A Circular Queue with Fixed Size

package main

import "fmt"

// Ring is a fixed-size queue that reuses its slots.
type Ring struct {
    slots []int
    head  int // index of the front item
    count int // how many items are stored
}

// NewRing makes an empty ring with room for size items.
func NewRing(size int) *Ring {
    return &Ring{slots: make([]int, size)}
}

// Enqueue adds a value at the back. It returns false when the ring is full.
func (ring *Ring) Enqueue(value int) bool {
    if ring.count == len(ring.slots) {
        return false // full
    }
    tail := (ring.head + ring.count) % len(ring.slots) // % wraps the index back to 0
    ring.slots[tail] = value
    ring.count++
    return true
}

// Dequeue removes the front value. It returns false when the ring is empty.
func (ring *Ring) Dequeue() (int, bool) {
    if ring.count == 0 {
        return 0, false
    }
    value := ring.slots[ring.head]
    ring.head = (ring.head + 1) % len(ring.slots) // move the front, wrapping around
    ring.count--
    return value, true
}

func main() {
    ring := NewRing(3)
    fmt.Println(ring.Enqueue(1), ring.Enqueue(2), ring.Enqueue(3), ring.Enqueue(4))
    first, _ := ring.Dequeue()
    fmt.Println("out:", first, "add 4:", ring.Enqueue(4))
    for ring.count > 0 {
        value, _ := ring.Dequeue()
        fmt.Print(value, " ")
    }
    fmt.Println()
}
true true true false
out: 1 add 4: true
2 3 4

The ring remembers where the front is (head) and how many items it holds (count). The % operator wraps the index back to 0, so freed slots are reused and no memory is wasted. Log buffers and network packet queues use rings like this.

Program 10: Queue Using Two Stacks

package main

import "fmt"

// TwoStackQueue pushes to inStack and pops from outStack.
// When outStack is empty, it moves everything from inStack, which flips the order.
type TwoStackQueue struct {
    inStack  []int
    outStack []int
}

// Enqueue adds a value to the back of the queue.
func (queue *TwoStackQueue) Enqueue(value int) {
    queue.inStack = append(queue.inStack, value)
}

// Dequeue removes and returns the oldest value.
func (queue *TwoStackQueue) Dequeue() int {
    // Step 1: if outStack is empty, pour inStack into it.
    if len(queue.outStack) == 0 {
        for len(queue.inStack) > 0 {
            top := queue.inStack[len(queue.inStack)-1]
            queue.inStack = queue.inStack[:len(queue.inStack)-1]
            queue.outStack = append(queue.outStack, top)
        }
    }
    // Step 2: the top of outStack is the oldest value.
    value := queue.outStack[len(queue.outStack)-1]
    queue.outStack = queue.outStack[:len(queue.outStack)-1]
    return value
}

func main() {
    var queue TwoStackQueue
    queue.Enqueue(1)
    queue.Enqueue(2)
    fmt.Print(queue.Dequeue(), " ") // moves 2, 1 into outStack, pops 1
    queue.Enqueue(3)
    fmt.Print(queue.Dequeue(), " ") // outStack still has 2
    fmt.Println(queue.Dequeue())    // outStack empty, so it moves 3
}
1 2 3

Pouring one stack into another flips the order, so the oldest item ends up on top. Each item moves from inStack to outStack only once. So the average cost per operation is O(1), which is called amortized O(1).

Go stack and queue programs comparison of a stack and a queue
A stack serves the newest item first, while a queue serves the oldest item first.

Program 11: Sliding Window Maximum with a Deque

package main

import "fmt"

// maxWindow returns the biggest value in every window of windowSize items.
// deque holds indexes, and their values always go from big to small.
func maxWindow(numbers []int, windowSize int) []int {
    var deque []int
    var result []int
    for i, value := range numbers {
        // Step 1: drop the front index if it has left the window.
        if len(deque) > 0 && deque[0] <= i-windowSize {
            deque = deque[1:]
        }
        // Step 2: drop smaller values from the back. They can never be the max now.
        for len(deque) > 0 {
            lastIndex := deque[len(deque)-1]
            if numbers[lastIndex] > value {
                break
            }
            deque = deque[:len(deque)-1]
        }
        // Step 3: add the current index at the back.
        deque = append(deque, i)
        // Step 4: once the first window is full, the front holds the max.
        if i >= windowSize-1 {
            result = append(result, numbers[deque[0]])
        }
    }
    return result
}

func main() {
    fmt.Println(maxWindow([]int{1, 3, -1, -3, 5, 3, 6, 7}, 3))
}
[3 3 5 5 6 7]

A deque lets you remove from both ends. Here you drop old indexes from the front and smaller values from the back. As a result, the front is always the window maximum.

Real-Life Go Stack and Queue Programs

Program 12: Undo and Redo with Two Stacks

package main

import (
    "fmt"
    "strings"
)

// Editor keeps the current words plus two stacks of saved snapshots.
type Editor struct {
    words     []string
    undoStack [][]string // each entry is a saved copy of words
    redoStack [][]string
}

// copyWords returns a new slice with the same words, so later changes cannot touch it.
func copyWords(words []string) []string {
    snapshot := make([]string, len(words))
    copy(snapshot, words) // copy fills snapshot with the items from words
    return snapshot
}

// Type saves the current words, then adds a new word.
func (editor *Editor) Type(word string) {
    editor.undoStack = append(editor.undoStack, copyWords(editor.words))
    editor.redoStack = nil // new typing clears redo; nil means empty
    editor.words = append(editor.words, word)
}

// Undo goes back to the last saved snapshot.
func (editor *Editor) Undo() {
    if len(editor.undoStack) == 0 {
        return
    }
    editor.redoStack = append(editor.redoStack, editor.words)
    editor.words = editor.undoStack[len(editor.undoStack)-1]
    editor.undoStack = editor.undoStack[:len(editor.undoStack)-1]
}

// Redo brings back the snapshot that Undo removed.
func (editor *Editor) Redo() {
    if len(editor.redoStack) == 0 {
        return
    }
    editor.undoStack = append(editor.undoStack, editor.words)
    editor.words = editor.redoStack[len(editor.redoStack)-1]
    editor.redoStack = editor.redoStack[:len(editor.redoStack)-1]
}

func main() {
    var editor Editor
    editor.Type("Go")
    editor.Type("is")
    editor.Type("fun")
    editor.Undo()
    fmt.Println(strings.Join(editor.words, " ")) // Join puts a space between words
    editor.Redo()
    fmt.Println(strings.Join(editor.words, " "))
}
Go is
Go is fun

Undo pops from one stack and pushes onto the other, and redo does the reverse. Before each change, Type saves a copy with copyWords. That way later typing cannot change an old snapshot.

Program 13: A Job Queue with a Buffered Channel

package main

import "fmt"

func main() {
    jobs := make(chan string, 3) // a channel with room for 3 items is a safe FIFO queue
    jobs <- "send email"         // <- sends a value into the channel
    jobs <- "resize image"
    jobs <- "write report"
    close(jobs) // no more jobs will be added

    for job := range jobs { // receives in the same order they were sent
        fmt.Println("done:", job)
    }
}
done: send email
done: resize image
done: write report

The jobs go in with <- and come out of range in the same order. A buffered channel is a queue that many goroutines can share safely, which makes it handy in concurrent Go stack and queue programs. See our Go channel programs for more.

Program 14: Reverse a Queue Using a Stack

package main

import "fmt"

func main() {
    queue := []int{1, 2, 3, 4}
    var stack []int

    // Step 1: dequeue everything onto the stack.
    for len(queue) > 0 {
        stack = append(stack, queue[0])
        queue = queue[1:]
    }
    // Step 2: pop everything back into the queue.
    for len(stack) > 0 {
        queue = append(queue, stack[len(stack)-1])
        stack = stack[:len(stack)-1]
    }
    fmt.Println(queue)
}
[4 3 2 1]

First, you take items from the front of the queue and push them on the stack. Then you pop them back, and the last item comes out first. Moving items through a stack flips their order. This idea is behind Program 10 too.

Stack vs Queue in Go Stack and Queue Programs

Both hold a list of waiting items, but they serve them in opposite orders. The table below compares them.

FeatureStackQueue
OrderLast in, first outFirst in, first out
Add with a sliceappend at the endappend at the end
Remove with a slicefrom the endfrom the front
Real exampleUndo, back buttonTicket line, job queue
Interview exampleValid parenthesesBFS in graphs

A simple rule helps. If the newest item matters most, use a stack. If fairness matters and the oldest item goes first, use a queue.

Common Mistakes in Go Stack and Queue Programs

  • Popping an empty stack: stack[len(stack)-1] panics when the length is 0, so check first.
  • Mixing up left and right: in postfix maths, the top of the stack is the second number.
  • Forgetting the final check: valid parentheses must also check that the stack is empty.
  • Holding big values in a slice queue: clear the front slot before queue[1:].
  • Sharing slices by mistake: copy a slice before saving it as an undo snapshot.

Best Practices for Go Stack and Queue Programs

  • Return an ok flag from Pop and Dequeue instead of panicking.
  • Use a ring buffer when the queue size is fixed.
  • Use a channel when several goroutines share the queue.
  • Store indexes, not values, in monotonic stacks and deques.
  • Write a small type with methods, so the rest of the code reads clearly.

Go Stack and Queue Programs Interview Questions and Answers

These are the stack and queue questions interviewers ask most, and they build on the Go stack and queue programs above. Each code answer is complete, with real output from Go 1.27.

Concept Questions on Go Stack and Queue Programs

Q1. What is the difference between LIFO and FIFO?

LIFO means last in, first out, which is how a stack works. FIFO means first in, first out, which is how a queue works.

Q2. Does Go have a built-in stack or queue?

No. You build them with a slice, container/list or a channel. A slice is the simplest and fastest for a single goroutine.

Q3. What does this program print?

package main

import "fmt"

func main() {
    stack := []int{1, 2, 3}
    top := stack[len(stack)-1] // read the top
    stack = stack[:len(stack)-1] // pop
    stack = append(stack, 9)     // push
    fmt.Println(top, stack)
}
3 [1 2 9]

The pop shrinks the length to 2, and the push writes 9 into the slot where 3 used to be.

Q4. What happens when you pop from an empty slice stack?

package main

import "fmt"

func main() {
    var stack []int
    fmt.Println(stack[len(stack)-1]) // len(stack)-1 is -1, which is not a valid index
}
panic: runtime error: index out of range [-1]

Always check len(stack) == 0 first, or return an ok flag as in Program 2.

Coding Questions

Q5. How do you reverse a string with a stack?

package main

import "fmt"

func main() {
    var stack []rune // a rune is one character
    for _, letter := range "golang" {
        stack = append(stack, letter) // push each letter
    }
    reversed := make([]rune, 0, len(stack)) // empty, with room for every letter
    for len(stack) > 0 {
        reversed = append(reversed, stack[len(stack)-1]) // pop gives letters in reverse
        stack = stack[:len(stack)-1]
    }
    fmt.Println(string(reversed))
}
gnalog

You push every letter, then pop them all, so they come out last letter first. We use runes, not bytes, so letters like “é” stay whole.

Q6. How do you find the length of the longest valid parentheses run?

package main

import "fmt"

// longestValid keeps the index of the last unmatched ')' at the bottom.
func longestValid(text string) int {
    best := 0
    stack := []int{-1} // start marker before the string
    for i, char := range text {
        if char == '(' {
            stack = append(stack, i)
            continue // go to the next character
        }
        stack = stack[:len(stack)-1] // match with the last '('
        if len(stack) == 0 {
            stack = append(stack, i) // new start marker
            continue
        }
        length := i - stack[len(stack)-1] // distance back to the marker
        if length > best {
            best = length
        }
    }
    return best
}

func main() {
    fmt.Println(longestValid(")()())"), longestValid("(()"), longestValid(""))
}
4 2 0

The marker at the bottom tells us where the current valid run started. So i minus the marker is the length of that run, and best keeps the biggest one.

Q7. How do you check if a stack of pushes and pops is valid?

package main

import "fmt"

// validSequence checks if popped could come from pushing pushed in order.
func validSequence(pushed, popped []int) bool {
    var stack []int
    popIndex := 0 // next value we expect to pop
    for _, value := range pushed {
        stack = append(stack, value)
        for len(stack) > 0 && stack[len(stack)-1] == popped[popIndex] {
            stack = stack[:len(stack)-1] // pop while the top matches
            popIndex++
        }
    }
    return len(stack) == 0
}

func main() {
    fmt.Println(validSequence([]int{1, 2, 3, 4, 5}, []int{4, 5, 3, 2, 1}))
    fmt.Println(validSequence([]int{1, 2, 3, 4, 5}, []int{4, 3, 5, 1, 2}))
}
true
false

We simulate the real stack. After each push, you pop as long as the top matches the next expected value. If anything is left at the end, the pop order was impossible.

Design Questions

Q8. When should you use a ring buffer instead of a slice queue?

Use a ring buffer when the maximum size is known, such as the last 100 log lines. It never grows, never copies and reuses the same memory forever.

Q9. Which graph search uses a queue, and which uses a stack?

Breadth-first search (BFS) uses a queue, so it visits nodes level by level. Depth-first search (DFS) uses a stack, or recursion, so it goes deep first. We build both in a later post in this series.

Q10. Is a channel a good general queue?

It is great between goroutines. Inside one goroutine, a slice is simpler and faster, because a channel adds locking and can block when full.

Practice Task

To practise Go stack and queue programs, write a function that takes daily temperatures like [73, 74, 75, 71, 69, 72, 76, 73] and returns how many days you must wait for a warmer day, giving [1 1 4 2 1 1 0 0]. Hint: use the monotonic stack from Program 6 and store indexes.

Official Resources

Quick Recap

  • Go stack and queue programs use slices: stacks work at the end, queues take from the front.
  • A stack matches brackets, evaluates postfix maths and powers undo.
  • With a second stack of minimums, a min stack answers Min in O(1).
  • A ring buffer gives a fixed-size queue that reuses memory.
  • Two stacks can make a queue, and a deque solves the sliding window maximum.

What’s Next?

Next, we build a structure that always gives you the smallest or biggest item first. Read Go heap programs, with container/heap, top K items and a priority queue. For more practice, see the Go linked list programs.