How to Implement Stack in Golang [Step by Step Guide]

How to Implement Stack in Golang [Step by Step Guide]

In this tutorial, we will learn about “how to implement Stack in Golang using step by step guide“. If you have ever come across Data Structures that talks about arranging and storing data in the memory in various way to utilize the memory efficiently, you must have heard about stack. The stack is one of the most common and usable data structure. This tutorial will help you to get the overview of stack data structure and the operations that are performed on a stack. We will also look at the stack implementation in the Golang. So let us begin the tutorial.

 

What is Stack?

A stack is a fundamental data structure that follows the Last in First out (LIFO) principle. In a stack, the last element added is the first one to be removed. To understand this better, let us take an example. Suppose you have stack of plates. You clean one plate at a time and keep it at the top of plate stack. When you need to take out a plate from the stack, you will always take out the plate from the top. This is exactly how the stack works. There are certain operations that are performed on the stack data structure. Let us look at  stack operations one by one in the next section.

 

Stack Operations

Push Operation

The Push operation is used to add an element to the top  of the stack. It increases the stack size by one. The new elements becomes the top of the stack. Let us understand this by taking some numbers as shown below. We have to add the numbers (9, 12, 4, 8, 3, 5) in the stack. As the index of stack starts from 0, the first element(9) will be pushed at index 0. The second element from the list(12) will be pushed at index 1 and so on.

 

Pop Operation

The Pop operation removes the element from the top of the stack. It decreases the stack size by one. After a Pop operation, the element that was on top is no longer in the stack. In the same example as above, let us perform the Pop operation and understand how the elements are removed from the stack. In the figure below, we see that the last element in the stack is 5. So, when we Pop from the array, 5 will be removed and now 3 will become the top element is the stack. Again, when we Pop the element from the stack this time 3 will be removed and 8 will become the top element in the stack.

 

 

Peek  Operation

The Peek operation returns the element at the top of the stack without removing it. It allows you to examine the element that would be removed next if a pop operation were performed. When we say top, it means the last element that is present in the stack is returned.

 

isEmpty Operation

This operation checks if the stack is empty. It returns true or a custom message if the stack has no elements. If elements are present in the stack, it will return false or a custom message saying stack is not empty.

 

Size Operation

The size operation returns the total number of elements currently in the stack. We can track the current size of the given stack by checking the size of it using the built-in function known as len().

 

How to Implement Stack in Golang [Step by Step Guide]

Also Read: How to Automatically Refresh Web Pages Using Golang

So far, we have learnt about the stack data structure and all its operation. Let us now implement stack and all the stack operation using the Golang code. Go through the below code and save it as say stack.go file.

package main

import "fmt"

type stack struct {
    data []int
}

//Push elements into Stack
func (s *stack) Push(val int) {

    s.data = append(s.data, val)
}

//Pop elements from Stack
func (s *stack) Pop() {

    s.data = s.data[:len(s.data)-1]
}

//Print Stack elements
func (s stack) PrintStack() {

    fmt.Println(s.data)
}

//Peek from the stack
func (s stack) Peek() int {

    last_element := s.data[len(s.data)-1]
    return last_element
}

//isEmpty Stack Operation
func (s stack) isEmpty() {

    if s.data == nil {
        fmt.Println("Stack is empty.")
    }
}

//Size of the Stack
func (s stack) Size() {

    fmt.Printf("Size of the stack is %d ", len(s.data))
    fmt.Println()
}

func main() {

    s1 := stack{}
    addSlice := []int{2, 4, 17, 10, 19, 3, 7}

    s1.isEmpty()

    for i := range addSlice {
        s1.Push(addSlice[i])
    }

    s1.Size()

    fmt.Println("Stack Data After Push operation: ")
    s1.PrintStack()

    fmt.Println("Stack Data After Pop operation: ")
    s1.Pop()
    s1.Pop()
    s1.PrintStack()

    fmt.Print("Element at the top of stack: ")
    elem := s1.Peek()
    fmt.Println(elem)

}
Code Explanation
1. I have created a struct which represent the stack.
2. I have created 6 functions, each implementing stack operations. These functions are, Push(), Pop(), PrintStack(), Peek(),  isEmpty(), Size().
3. I have created a main function inside which all

 

Let us understand each function usage and implementation explained below.
Push()
func (s *stack) Push(val int) {

    s.data = append(s.data, val)
}
Push() function will take aa value as argument and insert it in the stack. I have passed the stack pointer to function as we are directly making change to the stack. I have used append method to append each element in the stack.

 

Pop()

func (s *stack) Pop() {

    s.data = s.data[:len(s.data)-1]
}
Pop() function will take pointer to the stack struct as we have to remove element directly from the stack. Every time the Pop function is called, the stack size will be decreased by 1. This way every time the Pop function is called,  the last element from the stack is dereferenced.

 

PrintStack()

func (s stack) PrintStack() {

    fmt.Println(s.data)
}
PrintStack() function will take the copy of stack struct as this function will simply prints all the elements of the given stack whenever the PrintStack function is called.

 

Peek()

func (s stack) Peek() int {

    last_element := s.data[len(s.data)-1]
    return last_element
}
Peek() function will always return the element which is found at the top of the stack. The top of the stack means the element sitting at the end of the stack. We have created a variable called last_element which will always store the last element in the stack. Whenever the Peek function is called, the last_element will be returned by the function.

 

isEmpty()

func (s stack) isEmpty() {

    if s.data == nil {
        fmt.Println("Stack is empty.")
    }
}
isEmpty() function will check if the given stack is empty or not. To do so, we can compare the stack with the nil values at any given point. If the stack value becomes equal to nil, we will print the message saying that the stack is empty.

 

Size()

func (s stack) Size() {

    fmt.Printf("Size of the stack is %d ", len(s.data))
    fmt.Println()
}
Size() function will calculate the total stack size i.e total number of elements currently present in the stack. I have used the built-in len() function to calculate the size of the given stack.

 

Let us now execute the code and check the output it returns.
> go run .\stack.go
Stack is empty.
Size of the stack is 7 
Stack Data After Push operation: 
[2 4 17 10 19 3 7]
Stack Data After Pop operation: 
[2 4 17 10 19]
Element at the top of stack: 19

 

Summary

The stack operations are useful in various scenarios such as, managing function calls in a program, parsing expressions and undo mechanisms in applications. The simplicity and efficiency of stack operations make it a versatile data structure in computer science world.

Leave a Comment