Problem Solving with Go course

Stacks, Queues and SearchStacks from a Slice

Problem Solving with Go

Display

Theme

Stacks, Queues and Search · Test exercise

Stacks from a Slice

A stack is a pile: you put things on top and take them off the top. The last thing in is the first thing out (LIFO, last in, first out). Undo in an editor, matching brackets, walking back out of a maze: whenever you need to "go back to the most recent one", reach for a stack.

A slice is already a stack

Go has no stack type, and doesn't need one. A slice does both jobs:

var stack []int
stack = append(stack, 4) // push
stack = append(stack, 8)

top := stack[len(stack)-1]    // peek: 8
stack = stack[:len(stack)-1]  // pop

Pushing and popping at the end of a slice are both O(1). Always check len(stack) > 0 before popping: reading stack[-1] panics.

A stack for any type

If you push and pop in several places, wrap the slice in a type. With generics one definition works for int, string, Point or anything else:

type Stack[T any] struct {
	items []T
}

var history Stack[string]
var path Stack[Point]

T is a type parameter: Stack[string] is a stack whose T is string. Inside a method, var zero T gives you the zero value of whatever T is, which is handy for returning "nothing" from an empty stack.

Undo as a stack

Undo is the classic example. Before every change, push the current state. Undo pops the most recent state and restores it. A second undo pops the one before, and so on.

Task

This lesson's input is a list of commands for a tiny editor that starts with an empty text:

  • type <text> adds the text at the end (everything after the first space, spaces included);
  • delete <n> removes the last n characters, or everything if there are fewer;
  • undo reverts the most recent type or delete. With nothing to undo, it does nothing.
  1. Complete Push and Pop on Stack[T]. Pop returns ok == false when the stack is empty.
  2. Complete edit(commands []string) (string, error): run the commands and return the final text. Return an error for an unknown command or a delete count that isn't a whole number of zero or more.
main.go
package main

import (
	"bufio"
	"fmt"
	"os"
	"strings"
)

// Stack is a last-in, first-out pile of values of any type T.
type Stack[T any] struct {
	items []T
}

// Push puts v on top of the stack.
func (s *Stack[T]) Push(v T) {
	// TODO: append v to s.items
}

// Pop removes the top value and returns it. ok is false when the stack is empty.
func (s *Stack[T]) Pop() (v T, ok bool) {
	// TODO: take the last item off s.items
	return v, false
}

// Len returns how many values are on the stack.
func (s *Stack[T]) Len() int {
	return len(s.items)
}

// edit runs editor commands on an empty text and returns the final text:
// "type <text>" adds text at the end, "delete <n>" removes the last n characters,
// "undo" reverts the last type or delete (and does nothing when there is none).
func edit(commands []string) (string, error) {
	// TODO: before every type or delete, push the current text onto a Stack[string]
	return "", nil
}

func main() {
	var commands []string
	scanner := bufio.NewScanner(os.Stdin)
	for scanner.Scan() {
		commands = append(commands, strings.TrimSuffix(scanner.Text(), "\r"))
	}
	text, err := edit(commands)
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Printf("%q\n", text)
}
Go runtime not loaded yet

7 lines · 82 B of the 1 MB limit. Submit always uses the lesson's own input.