Golang program to implement stack data structure


In Golang, a stack is a linear data structure that works on the Last-In-First-Out (LIFO) principle which means that the element which is pushed in the stack in last will be popped out first. We will use two methods to implement the stack data structure using slice of integers and struct. Let’s see different examples to understand the concept.

Method 1: Using Slice of Integers

Here, in this method, Go employs two functions, Push and Pop, to add and remove values from the top of the stack, respectively, and a slice of integers to store the values in the stack. The Push function adds an integer to the end of the slice from the input. The Pop function takes the value from the slice's end and returns it. By examining the length of the slice, the IsEmpty method determines whether the stack is empty. The Push and Pop functions are used in the main function to add and remove values from the stack, and the IsEmpty function is used to determine whether the stack is empty.

Algorithm

  • Step 1 − Create a package main and declare fmt(format package) package in the program where main produces executable codes and fmt helps in formatting input and output.

  • Step 2 − Make a slice of integers called a Stack type.

  • Step 3 − Then, to add a value to the top of the stack, use the Push method.

  • Step 4 − Stack and an integer v are the inputs.

  • Step 5 − The stack with v is added to the top as the result

  • Step 6 − In the next step to remove and return the top value from the stack, implement the Pop method.

  • Step 7 − The stack's top value and the stack with the top value are deleted as output.

  • Step 8 − To determine if the stack is empty, implement the IsEmpty function.

  • Step 9 − The output will be a boolean value indicating if the stack is empty.

  • Step 10 − Create a Stack type instance, add some values using the Push method, and delete some values using the Pop method in the main function. Finally, use the IsEmpty function to see whether the stack is empty.

Example

In this example we will use slice of integers to implement stack data structure. Let’s see through the code.

package main
import "fmt"

type Stack []int   //stack

// Push adds a value to the top of the stack.
func (st *Stack) Push(v int) {
   *st = append(*st, v)
}

// Pop removes and returns the top value from the stack.
func (st *Stack) Pop() int {
   if st.IsEmpty() {
      return 0
   }
   top := (*st)[len(*st)-1]
   *st = (*st)[:len(*st)-1]
   return top
}

func (st *Stack) IsEmpty() bool {
   return len(*st) == 0
}

func main() {
   st := Stack{}
   st.Push(1)
   st.Push(2)
   fmt.Println("The value popped from the stack is given as:")
   fmt.Println(st.Pop())
   fmt.Println(st.Pop())
   fmt.Println("Is the stack empty?")
   fmt.Println(st.IsEmpty())
}

Output

The value popped from the stack is given as:
2
1
Is the stack empty?
true

Method 2: Using Struct

In this approach, the values of the stack are stored in a struct, and the index of the top value in the stack is tracked by a top variable. The Push method adds a new value to the end of the values slice after increasing the top variable. The Pop method decrements the top variable, obtains the value at the current top index, and returns it. If the top variable equals -1, indicating that there are no values on the stack, the IsEmpty method returns true. Let’s see through the code and the algorithm.

Algorithm

  • Step 1 − Create a package main and declare fmt(format package) package in the program where main produces executable codes and fmt helps in formatting input and output.

  • Step 2 − Make a stack structure with values and top as its two fields. Here, top is an integer that tracks the index of the top value in the stack, and values is a slice of integers.

  • Step 3 − In the next step, create a function called NewStack that returns a fresh instance of the Stack struct that has a top value of -1 and an empty slice of values.

  • Step 4 − Then, use a Push method to push a value to the top of the stack.

  • Step 5 − The input will be a Stack struct instance and integer value.

  • Step 6 − The output will be the stack with the most recent value at the top.

  • Step 7 − Then, implement a Pop method that takes the top value off the stack and returns it.

  • Step 8 − In the next case, an instance of the Stack struct will be the input.

  • Step 9 − The output will be the stack's highest value and that value will be removed.

  • Step 10 − Implement a true-returning IsEmpty method to determine whether the stack is empty.

  • Step 11 − The output will be a boolean value indicating if the stack is empty.

  • Step 12 − Create a Stack type instance using the NewStack function in the main function, then add and delete values using the Push and Pop methods. Finally, use the IsEmpty function to see whether the stack is empty.

  • Step 13 − The print statements are executed using fmt.Println() method where ln means new line.

Example

In this example we will use stack struct to implement stack data structure. Let’s see through the code.

package main
import "fmt"

type Stack struct { //stack
   values []int 
   top    int
}

func NewStack() *Stack {
   return & Stack{
      values: make([]int, 0),
      top:    -1,
   }
}

// Push adds a value to the top of the stack.
func (st *Stack) Push(value int) {
   st.top++
   st.values = append(st.values, value)
}

// Pop removes and returns the top value from the stack.
func (st *Stack) Pop() int {
   if st.IsEmpty() {
      return 0
   }
   value := st.values[st.top]
   st.top--
   return value
}

func (st *Stack) IsEmpty() bool {
   return st.top == -1
}

func main() {
   st := NewStack()
   st.Push(1)
   st.Push(2)
   fmt.Println("The value popped from the stack is given as:")
   fmt.Println(st.Pop())
   fmt.Println(st.Pop())
   fmt.Println("Is the stack empty?")
   fmt.Println(st.IsEmpty())
}

Output

The value popped from the stack is given as:
2
1
Is the stack empty?
true

Conclusion

We executed the program of implementing stack data structure using two methods. In the first method we used slice of integers and in the second method we used stack struct.

Updated on: 20-Feb-2023

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements