Skip to content

Instantly share code, notes, and snippets.

@lkrych
Created August 5, 2018 18:23
Show Gist options
  • Save lkrych/138bbab9bb553069f4291d8e7bfa0ea1 to your computer and use it in GitHub Desktop.
Save lkrych/138bbab9bb553069f4291d8e7bfa0ea1 to your computer and use it in GitHub Desktop.
Linked list implementation of stack in go
type Node struct {
val int
next *Node
}
type LinkedList struct {
head *Node
}
func (ll *LinkedList) insert(n int) {
//add to front of linked list
newNode := &Node{
val: n,
next: nil,
}
newNode.next = ll.head
ll.head = newNode
}
func (ll *LinkedList) removeFirstNode() *Node {
firstNode := ll.head
ll.head = ll.head.next
return firstNode
}
type Stack struct {
data LinkedList
size int
}
func (s *Stack) push(n int) {
s.data.insert(n)
s.size = s.size + 1
}
func (s *Stack) pop() int {
first := s.data.removeFirstNode()
s.size = s.size - 1
return first.val
}
func (s *Stack) isEmpty() bool {
return s.size == 0
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment