CS의 기초 다시 배우기 - 스택 구현

Susan Sarandon
풀어 주다: 2024-10-14 06:17:02
원래의
447명이 탐색했습니다.

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())
}
로그인 후 복사

위 내용은 CS의 기초 다시 배우기 - 스택 구현의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

원천:dev.to
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
저자별 최신 기사
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!