DEV Community

Cover image for Relearning Basics of CS - Implementing Stack
urulaik
urulaik

Posted on

Relearning Basics of CS - Implementing Stack

I have been trying to learn a new programming language and what better way to do it than start from the basics. In this series of posts that come I will attempt to implement a simple Data structure and algorithms using Go. 

In the book An Introduction to algorithms By CLRS in the chapter of Elementary data structure the first data structure that is being talked about is the stack.

What is a Stack

Stack is a simple data structure that is used to store a set of items. The properties of a stack are that it allows us to add an item to the top of the stack and remove from the stack so it follows a Last In First Out principle or LIFO.

The insert operation is called a Push and the remove operation is called a Pop. Since we dont want to have an empty stack pop and deal with memory errors we also implement a check for whether a Stack is empty or not. Fairly simple data structure.

Below you can find the implementation of the stack in golang. The time complexity is O(N) and space complexity of using a stack is O(1)

package main

import "fmt"

type Stack []int

func (stack *Stack) Push (value int){
    *stack = append(*stack, value)
}

func (stack *Stack) Pop () int{
    if stack.IsEmpty() {
        return 0
    }
    top := (*stack)[len(*stack)-1]
    *stack = (*stack)[:len(*stack)-1]
    return top
}

func (stack *Stack) IsEmpty() bool{
    return len(*stack) == 0
}


func main(){
    st := Stack{}
    st.Push(1)
    st.Push(2)
    fmt.Println(st.Pop())
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)