8

A basic stack (LIFO) data structure

 3 years ago
source link: https://yourbasic.org/golang/implement-stack/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

A basic stack (LIFO) data structure

yourbasic.org/golang
stack-of-apples.jpg

The idiomatic way to implement a stack data structure in Go is to use a slice:

  • to push you use the built-in append function, and
  • to pop you slice off the top element.
var stack []string

stack = append(stack, "world!") // Push
stack = append(stack, "Hello ")

for len(stack) > 0 {
    n := len(stack) - 1 // Top element
    fmt.Print(stack[n])

    stack = stack[:n] // Pop
}
Hello world!

Performance

pink-coins-thumb.jpg

Appending a single element to a slice takes constant amortized time. See Amortized time complexity for a detailed explanation.

If the stack is permanent and the elements temporary, you may want to remove the top element before popping the stack to avoid memory leaks.

// Pop
stack[n] = "" // Erase element (write zero value)
stack = stack[:n]

More code examples

Go blueprints: code for com­mon tasks is a collection of handy code examples.

Share:             


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK