Golang program to reverse a string using stacks


In this article, we will see how to reverse a string using stacks with Go Programming. A stack is a Last In First Out (LIFO) compliant data structure in Go. This implies that the first element to be eliminated will be the one that was most recently added to the stack. A doubly-linked list is implemented in the built-in Go package "container/list" and can be used to build a stack. Slices (dynamic arrays) are frequently used to implement stacks in Go, though. Let’s see how it’s executed using different set of examples.

Method 1: Converting the string to slice of runes

In this method, we will see how to reverse a string using stacks by converting the string to slice of runes. Runes are Go's equivalent of characters thus it first slices the string into them before pushing each one into the stack. The next step is to remove each rune from the stack and add it to a fresh string. As a result, the original string is turned around. The reverse function is then used on a string by the main function, which prints both the original and the inverted string. Let’s see its execution.

Syntax

func append(slice, element_1, element_2…, element_N) []T

The append function is used to add values to an array slice. It takes number of arguments. The first argument is the array to which we wish to add the values followed by the values to add. The function then returns the final slice of array containing all the values.

Algorithm

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

  • Step 2 − Create a function reverse and make a variable to store the reversed string and an empty stack to hold it.

  • Step 3 − Transform the input string taken into the function into a rune slice.

  • Step 4 − Push each rune from the slice onto the stack one at a time.

  • Step 5 − Pop each rune off the stack and add it to the inverted string as you go through the st ack.

  • Step 6 − Return the string that has been reversed as the result.

  • Step 7 − Call the function reverse from the main function with one argument of a string which is to be reversed.

  • Step 8 − The reversed string is printed on the console using fmt.Println() function where ln means new line.

Example

In the following example, we are going to reverse the strings by converting the strings to slices of runes.

package main
import (
   "fmt"
)

func reverse(str string) string {
   runes := []rune(str)   //convert the string to slice of runes
   var stack []rune
   for _, v := range runes {
      stack = append(stack, v)     //push rune in the slice 
   }
   var reversed string
   for i := len(stack) - 1; i >= 0; i-- {
      reversed += string(stack[i])
   }
   return reversed     //return reversed string
}

func main() {
   original := "Hello, alexa!"
   fmt.Println("The original string given here is:", original)
   reversed := reverse(original)
   fmt.Println("The reversed string here is:", reversed) //print reversed string
}

Output

The original string given here is: Hello, alexa!
The reversed string here is: !axela ,olleH

Method 2: Using stacks with the help of struct in example

In this method, we will use struct to reverse a string. The Stack struct, which implements the Push and Pop methods to add and remove items from the stack, is used in the aforementioned program. In the main function, each character from the input string is placed into the stack using a for loop after creating an instance of the Stack struct. Each character is taken off of the stack using a second for loop, added to a new string, and then printed as the inverted string. Let’s see its execution.

Algorithm

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

  • Step 2 − Incorporate the Push and Pop functions into a struct called Stack to add and remove things from the stack, respectively.

  • Step 3 − Initialize a Stack struct instance in the main function and take a string that has to be reversed as an input.

  • Step 4 − Push each character of the input string onto the stack using the Push technique using a for loop.

  • Step 5 − Create a blank string with the name reversed.

  • Step 6 − Use a second for loop to add each character to the reversed string by using the Pop function to remove them from the stack.

  • Step 7 − Print the reversed string as an output using fmt.Println() function where ln means new line.

  • Step 8 − As we iterate through the string twice, once to place the character on the stack and once to pop it from the stack, the overall time complexity of this approach is O(n), where n is the length of the input string. Due to the use of a second stack to hold the characters, the space complexity of this technique is also O(n).

Example

In the following example, we are going to reverse the strings by using stacks with the help of struct in example

package main
import "fmt"

type Stack struct { // Stack struct
   items []rune
}

func (str *Stack) Push(item rune) { //push method to items in stack
   str.items = append(str.items, item)
}

func (str *Stack) Pop() rune { //pop method to pop items from the stack
   item := str.items[len(str.items)-1]
   str.items = str.items[:len(str.items)-1]
   return item
}

func main() {
   stack := &Stack{}   //create a stack
   str := "hello alexa"  //create a string
   fmt.Println("The original string is:", str)	
   for _, char := range str {
      stack.Push(char)
   }
   reversed := ""  //create empty string to add reversed string
   for i := 0; i < len(str); i++ {
      reversed += string(stack.Pop())  //pop items from stack and add to newly created string
   }
   fmt.Println("The reversed string is:")
   fmt.Println(reversed) // Output: "dlrow olleh"
}

Output

The original string is: hello alexa
The reversed string is:
axela olleh

Conclusion

We executed the program of reversing a string using stack with the help of different examples. In the first example we converted the string to slice of runes and in the second method we used the struct to execute the function.

Updated on: 20-Feb-2023

245 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements