Go Struct And Stack Data Structure

phuctm97

Minh-Phuc Tran

Posted on November 14, 2020

Go Struct And Stack Data Structure

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.

image.png


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())
    }
}
Enter fullscreen mode Exit fullscreen mode

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) šŸ˜‰

šŸ’– šŸ’Ŗ šŸ™… šŸš©
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.

Related