Implementing Stack Data Structure in Golang

implementing stack, last in first out (LIFO) data structure in golang#

stack is data structure which is used to solve many problems in programming world.

it is like we are keeping books one after another and in that we can’t remove first book because it is in the bottom we can only remove top one first and so on, we call it last in first out (LIFO).

we will create user defined type Stack which is a type of []int slice of int.

and then attach a methods on that Stack type like Top(), Pop() and Push().

Top() method will simply return the last element of that array slice.

Pop() method will simple remove the last element from the array.

Push() method will add element at the end of the array slice.

look at the below code for complete example.


package main

import "fmt"

type Stack []int

func (s *Stack) Top() int {
	return (*s)[len(*s)-1]
}
func (s *Stack) Pop() {
	(*s) = (*s)[:len(*s)-1]
}
func (s *Stack) Push(v int) {
	(*s) = append(*s, v)
}

func main() {
	
	arr := []int{1, 4, 6}
	stack := Stack(arr)
	fmt.Println(stack.Top())
	stack.Pop()
	fmt.Println(stack)
	stack.Push(10)
	fmt.Println(stack)
	stack.Push(12)
	fmt.Println(stack)
	stack.Pop()
	fmt.Println(stack)
	
}


output#

[1 4 6]
Top =>  6
After Pop =>  [1 4]
After Push =>  [1 4 10]
[1 4 10 12]
[1 4 10]

comments powered by Disqus