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.
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 중국어 웹사이트의 기타 관련 기사를 참조하세요!