Go Data Structures: Implementing stack using golang

A stack is an abstract data type that follows FILO (First-In-Last-Out) principle while inserting and deleting elements. Which means the element which is inserted first will be deleted last and the element inserted last will be deleted first. Stack can be implemented using arrays or linked list. Here we are creating stack using arrays in golang. Knowledge of golang slices will be an added advantage.

Basic operation of Stack

These are the operations we are going to implement

Push: Adds element to the top of the stack and return “Stack Overflow” if the stack is full.

Pop: Removes the top most element from the stack and return “Stack Underflow” if the stack is empty.

isEmpty: Check if the stack is empty.

isFull: Check if the stack is full

Peek: Return the top most element from the stack.

Display: Display the items of stack

Implementing the stack

We will create stack as a struct with two fields.

items is used to store stack elements. interface type is used to store elements of different datatype.

top is used to point to the topmost element of the stack. Initially, value of top will be -1. During a push operation, top will be increased and for during pop, top will be decreased. top is also used to check if the stack is full or empty.

stackSize is the size of the stack

Implementing stack operations

In line 2, we are checking if the stack is full and return “Stack Overflow”.

If stack is not full, we are inserting value to stack and incrementing value of top.

In line 2, we are checking if stack is empty and print “Stack Underflow”.

In line 7, we fetch the last element which is to be popped form the stack. In line 8, we are removing the last element from the slice and then decreases value of top. In line 10, we returns the popped element.

We are checking if value of top is -1 or not. If it is -1, then stack is empty else stack is not empty.

We are checking if top is equal to stackSize -1. If it is, then stack is full else stack is not full.

Peek operation returns the topmost element without removing it form the stack. We first check if the stack is empty, if not then we will return topmost element of the stack.

We iterate through items array and print the elements to display the stack.

Stack has many applications like infix to postfix conversion, reverse a word and also used in compilers. This was a quick introduction to implement stack using golang. All the above stack operations can be implemented in multiple ways but the concept remains same. Full code can be found here

Golang | Node.js | albinjose.me