Skip to content

Instantly share code, notes, and snippets.

@bemasher
Last active August 19, 2020 10:59
Show Gist options
  • Save bemasher/1777766 to your computer and use it in GitHub Desktop.
Save bemasher/1777766 to your computer and use it in GitHub Desktop.
A simple LIFO stack backed by a linked list implemented with golang.
package main
import (
"fmt"
)
type Stack struct {
top *Element
size int
}
type Element struct {
value interface{} // All types satisfy the empty interface, so we can store anything here.
next *Element
}
// Return the stack's length
func (s *Stack) Len() int {
return s.size
}
// Push a new element onto the stack
func (s *Stack) Push(value interface{}) {
s.top = &Element{value, s.top}
s.size++
}
// Remove the top element from the stack and return it's value
// If the stack is empty, return nil
func (s *Stack) Pop() (value interface{}) {
if s.size > 0 {
value, s.top = s.top.value, s.top.next
s.size--
return
}
return nil
}
func main() {
stack := new(Stack)
stack.Push("Things")
stack.Push("and")
stack.Push("Stuff")
for stack.Len() > 0 {
// We have to do a type assertion because we get back a variable of type
// interface{} while the underlying type is a string.
fmt.Printf("%s ", stack.Pop().(string))
}
fmt.Println()
}
@hemantasapkota
Copy link

Excellent. I've used this as the main data structure for computing convex hull in 2D.
https://github.com/hemantasapkota/go-convexhull

Thanks.

@alinz
Copy link

alinz commented Nov 21, 2014

Thanks for the simple implementation. I have upgraded it and added Peek. One enhancement that I added is exists variable.
here's the link which I have incorporated into one of my project: https://github.com/alinz/gonote/blob/master/note/util/stack.go

Thanks.

@tooolbox
Copy link

Thanks for the implementation example! I probably would have used a slice or something silly.

Used this as the basis for a typed stack here:
https://github.com/tooolbox/go-xib-strings/blob/master/stack.go

Thanks again.

@junpengxxx
Copy link

According to ur design, I implement another version of stack via Slice. Which will be used in one of my project.

This is the stack link : https://github.com/tonyshaw/Stack

Thanks.

@markturansky
Copy link

Let me add my thanks, too!

I added @alinz Peep and I added a PopLast and maximum capacity.

https://gist.github.com/markturansky/3f2273ae39f970ff56ff22a047cc6345

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment