Skip to content

Instantly share code, notes, and snippets.

@SteveBate
Created September 27, 2015 08:08
Show Gist options
  • Save SteveBate/acbe7f863012890b7388 to your computer and use it in GitHub Desktop.
Save SteveBate/acbe7f863012890b7388 to your computer and use it in GitHub Desktop.
A stack implemented in Go using a linkedlist data structure
package main
import (
"errors"
"fmt"
"log"
)
type ListNode struct {
number int
next *ListNode
}
type IntStack struct {
head *ListNode
}
func (i *IntStack) Push(value int) {
if i.head == nil {
i.head = &ListNode{number: value, next: nil}
} else {
i.head = &ListNode{number: value, next: i.head}
}
}
func (i *IntStack) Pop() int {
if i.head == nil {
log.Panic(errors.New("stack is empty"))
}
value := i.head.number
i.head = i.head.next
return value
}
func (i *IntStack) Peek() int {
if i.head == nil {
return -1
}
return i.head.number
}
func main() {
st := IntStack{}
st.Push(1)
st.Push(2)
st.Push(3)
st.Push(4)
fmt.Println("popped: ", st.Pop())
fmt.Println("popped: ", st.Pop())
fmt.Println("popped: ", st.Pop())
fmt.Println("on stack: ", st.Peek())
fmt.Println("popped: ", st.Pop())
fmt.Println("on stack: ", st.Peek())
// empty stack error
fmt.Println(st.Pop())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment