Stack with Go

Stack is a LIFO(Last In, First Out) data structure, frequently used in computer science and software engineering.

Unlike many other commonly used languages, go doesn’t provide standardized stack implemtation. So, in order to use stack, the developer should create his own.

ADT(Abstract Data Types)

Let’s dive in and implement the following 6 methods.

  • push: add item on top of the stack
  • pop: retrieve the item on top of the stack
  • peek: show(but not pop) the item on top of the stack
  • isEmpty: return true if it is empty, else false
  • getSize: return the number of items in the stack

Implementation

Stack can be implemented both by using the array and the linked list. In this article, we’re going to use a linked list concept in order to make our stack to have elastic size.

package stack

type (
    Stack struct {
        top *node
        size int
    }
    node struct {
        prev *node
        val interface{}
    }
)

//Constructor
func NewStack() *Stack{
    return &Stack{nil, 0}
}

// push
func (s *Stack) push(val interface{}) {
    newNode := &node {s.top, val}
    s.top = newNode
    s.size++
}

// pop
func (s *Stack) pop() interface{} {
    if s.size == 0 {
        return nil
    }
    popped := s.top
    s.top = popped.prev
    s.size--

    return popped.val
}

// peek
func (s *Stack) peek() interface {} {
    if s.size == 0 {
        return nil
    }

    return s.top.val
}

// isEmpty
func (s *Stack) isEmpty() bool {
    return s.size == 0
}

// getSize
func (s *Stack) getSize() int {
    return s.size
}