Golang Reverse Array with Stack

To reverse the elements of an array using a stack, follow these steps:

  1. Create a stack structure for storing elements of an array.
  2. Iterate through the array and push each element into the stack sequentially.
  3. Create a new array to store the reversed elements.
  4. Pop elements from the stack one by one and add them to a new array.
  5. Return a new array as the result of reversing.

The following is an example code implementation:

package main

import (
	"fmt"
)

type Stack struct {
	data []int
}

func (s *Stack) push(val int) {
	s.data = append(s.data, val)
}

func (s *Stack) pop() int {
	if len(s.data) == 0 {
		return 0
	}
	val := s.data[len(s.data)-1]
	s.data = s.data[:len(s.data)-1]
	return val
}

func reverseArray(arr []int) []int {
	stack := Stack{}
	for _, val := range arr {
		stack.push(val)
	}

	var reversed []int
	for len(stack.data) > 0 {
		reversed = append(reversed, stack.pop())
	}

	return reversed
}

func main() {
	arr := []int{1, 2, 3, 4, 5}
	reversed := reverseArray(arr)
	fmt.Println(reversed)
}

In the example above, we defined a Stack structure to implement stack operations. Then, we used the reverseArray function to reverse the elements of the array. By calling the reverseArray function and passing in the array parameter, we can get the reversed result.

bannerAds