Golang program to reverse a stack


In this Golang article, we are going to reverse a stack using recursive and iterative method. A stack is a linear data structure that follows the Last-In-First-Out (LIFO) principle.

Algorithm

  • Step 1 − First, we need to import the fmt and strconv package.

  • Step 2 − Create a stack structure with an item slice to store the stack elements.

  • Step 3 − Now, define the functions, push(), pop(), peek(), isEmpty() and print() to perform the basic operations with the stack.

  • Step 4 − push() adds the item to the end of the stack while pop() removes the last item from the stack. And peek() returns the last item from the stack, without removing it.

  • Step 5 − isEmpty() returns true if the stack is empty otherwise false and print() prints the items of the stack.

  • Step 6 − Now, create reverseS() function to reverse the stack. Firstly, it checks if the stack is empty or not. Then, it returns the elements of the stack in the reversed manner.

  • Step 7 − It pops an item from the top of the stack and stores it in a variable temp. Then, it calls itself recursively to reverse the rest of the stack. After the stack is reversed, it calls insert() function to insert the popped item at the bottom of the reversed stack.

  • Step 8 − insert() function inserts an item at the bottom of the stack. If the stack is empty, it pushes the item onto the stack and returns.

  • Step 9 − If the stack is not empty, it pops an item from the top of the stack and calls itself recursively to insert the item at the bottom. After the item is inserted at the bottom, it pushes the popped item back onto the stack.

  • Step 10 − Start the main() function. Inside the main() function, create a stack struct and initialize a stack with some items.

  • Step 11 − Print the initial stack elements.

  • Step 12 − Now, call the reverseS() function and pass the stack to it as argument.

  • Step 13 − Further, print the reversed stack elements using the print() function.

Example 1

In this example, we will define a reverseS() function that is used to reverse a stack using recursion method.

package main

import (
   "fmt"
   "strconv"
)

type Stack struct {
   items []int
}

func (s *Stack) push(item int) {
   s.items = append(s.items, item)
}

func (s *Stack) pop() int {
   l := len(s.items) - 1
   item := s.items[l]
   s.items = s.items[:l]
   return item
}
func (s *Stack) peek() int {
   return s.items[len(s.items)-1]
}

func (s *Stack) isEmpty() bool {
   return len(s.items) == 0
}

func (s *Stack) print() {
   for _, item := range s.items {
      fmt.Print(strconv.Itoa(item) + " ")
   }
   fmt.Println()
}

func reverseS(s *Stack) {
   if s.isEmpty() {
      return
   }

   temp := s.pop()
   reverseS(s)
   insert(s, temp)
}

func insert(s *Stack, item int) {
   if s.isEmpty() {
      s.push(item)
      return
   }

   temp := s.pop()
   insert(s, item)
   s.push(temp)
}

func main() {
   s := &Stack{}

   s.push(3)
   s.push(6)
   s.push(2)
   s.push(5)
   s.push(8)
   fmt.Println("Initial stack:")
   s.print()

   reverseS(s)

   fmt.Println("Updated Reversed stack:")
   s.print()
}

Output

Initial stack:
3 6 2 5 8 
Updated Reversed stack:
8 5 2 6 3 

Example 2

In this example, we will define a reverseS() function that is used to reverse a stack using iterative method.

package main

import (
   "fmt"
)

type Stack struct {
   items []int
}

func (s *Stack) push(item int) {
   s.items = append(s.items, item)
}

func (s *Stack) pop() int {
   l := len(s.items) - 1
   item := s.items[l]
   s.items = s.items[:l]
   return item
}

func (s *Stack) peek() int {
   return s.items[len(s.items)-1]
}

func (s *Stack) isEmpty() bool {
   return len(s.items) == 0
}

func (s *Stack) reverseS() {
   if s.isEmpty() {
      return
   }

   stackSize := len(s.items)
   for i := 0; i < stackSize/2; i++ {
      temp := s.items[i]
      s.items[i] = s.items[stackSize-i-1]
      s.items[stackSize-i-1] = temp
   }
}

func (s *Stack) print() {
   for _, item := range s.items {
      fmt.Printf("%d ", item)
   }
   fmt.Println()
}

func main() {
   s := &Stack{}

   s.push(6)
   s.push(3)
   s.push(8)
   s.push(2)
   s.push(9)

   fmt.Println("Initial stack:")
   s.print()

   s.reverseS()
   fmt.Println("Updated Reversed stack:")
   s.print()
}

Output

Initial stack:
6 3 8 2 9 
Updated Reversed stack:
9 2 8 3 6 

Conclusion

We have successfully compiled and executed a go language program to to reverse a stack using recursive and iterative method along with two examples. In the first example, we have used the recursion method and in the second example, we have used the iterative method.

Updated on: 03-Apr-2023

127 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements