Stacks in go and python

Using list as a stack in python

Stacks come very handy in solving some of the problems. Often using just an array does the purpose rather than specific data structures.

In python to use a list as a stack is straight forward with append and pop methods already available.

if __name__ == '__main__':
    st = []
    for i in range(10):
        st.append(i)
    
    for i in range(10):
        top = st.pop()
        print(top)

Using slices as a stack in go

In go to use slices as a stack, push and pop methods are missing. These methods can be added quickly in the problem. Below is an example.

func push(arr *[]int, num int) {
	*arr = append(*arr, num)
}

func pop(arr *[]int) (error, int) {
	n := len(*arr)
	if n == 0 {
		return fmt.Errorf("stack is empty"), 0
	}
	top := (*arr)[n-1]
	*arr = (*arr)[:n-1]
	return nil, top
}

func main() {
	st := make([]int, 0)
	for i := 0; i < 10; i++ {
		push(&st, i)
	}
	for i := 0; i < 10; i++ {
		_, top := pop(&st) // Check for the error, before using top.
		fmt.Println(top)
	}
}
comments powered by Disqus