Created
August 5, 2018 18:23
-
-
Save lkrych/138bbab9bb553069f4291d8e7bfa0ea1 to your computer and use it in GitHub Desktop.
Linked list implementation of stack in go
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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