Go Struct And Stack Data Structure
Minh-Phuc Tran
Posted on November 14, 2020
A byte-sized article that can teach or remind you of a programming concept and/or language in <2 minutes.
Stack
Stack is a LIFO (last-in-first-out) data structure. It's usually used to convert a recursive solution into an iterative solution.
ā¹ļø It is asked a lot during technical interviews at big tech companies.
Golang implementation
Interestingly enough, there's no built-in implementation of Stack in Go, you'll have to implement it based on a linked list.
import "container/list" // import a package in Golang
type Stack struct { // how a struct is defined
list *list.List // lowercase var/function is private
}
func (s *Stack) Push(val int) { // upperccase var/function is public
s.list.PushBack(val)
}
func (s *Stack) Pop() int { // how a struct's function is defined
item := s.list.Back()
val := item.Value.(int)
s.list.Remove(item)
return val
}
func (s *Stack) Clean() {
for s.list.Len() > 0 { // there's no 'while' in Golang, only 'for'
s.list.Remove(s.list.Back())
}
}
Hope you learned something new from this article š!
If you have any comments, please leave them below. You can always DM and ask me anything on Twitter (@phuctm97) š
š šŖ š
š©
Minh-Phuc Tran
Posted on November 14, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.