Relearning Basics of CS - Implementing Stack

Susan Sarandon
Release: 2024-10-14 06:17:02
Original
446 people have browsed it

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())
}
Copy after login

The above is the detailed content of Relearning Basics of CS - Implementing Stack. For more information, please follow other related articles on the PHP Chinese website!

source:dev.to
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!