Skip to content

Instantly share code, notes, and snippets.

@iFurySt
Last active February 4, 2021 06:25
Show Gist options
  • Save iFurySt/86b532875848c8962eba6e03cce71c79 to your computer and use it in GitHub Desktop.
Save iFurySt/86b532875848c8962eba6e03cce71c79 to your computer and use it in GitHub Desktop.
Go - Stack(LIFO)
/**
* Package stack
* @Author iFurySt <[email protected]>
* @Date 2021/2/4
*/
package stack
import "fmt"
func Example() {
// Create a new stack and put some numbers in it.
s := New()
s.Push(3)
fmt.Println(s.IsEmpty())
fmt.Println(s.Peek())
s.Push(4)
fmt.Println(s.Pop())
// Output:
// false
// 3
// 4
}
/**
* Package container
* @Author iFurySt <[email protected]>
* @Date 2021/2/4
*/
package stack
type Stack []int
func New() Stack {
return Stack{}
}
// Push pushes an item onto the top of this stack
func (s *Stack) Push(elem int) {
*s = append(*s, elem)
}
// Pop removes the element at the top of this stack and return the element
func (s *Stack) Pop() (elem int) {
n := len(*s) - 1
elem = (*s)[n]
*s = (*s)[:n]
return elem
}
// IsEmpty checks if this stack is empty
func (s *Stack) IsEmpty() bool {
return len(*s) == 0
}
// Peek looks at the element at the top of this stack without removing it from the stack
func (s *Stack) Peek() int {
return (*s)[len(*s)-1]
}
// Len gets the length of this stack
func (s *Stack) Len() int {
return len(*s)
}
/**
* Package container
* @Author iFurySt <[email protected]>
* @Date 2021/2/4
*/
package stack
type Stack []int
func New() Stack {
return Stack{}
}
// Push pushes an item onto the top of this stack
func (s *Stack) Push(elem int) {
*s = append(*s, elem)
}
// Pop removes the element at the top of this stack and return the element
func (s *Stack) Pop() (elem int) {
n := len(*s) - 1
elem = (*s)[n]
*s = (*s)[:n]
return elem
}
// IsEmpty checks if this stack is empty
func (s *Stack) IsEmpty() bool {
return len(*s) == 0
}
// Peek looks at the element at the top of this stack without removing it from the stack
func (s *Stack) Peek() int {
return (*s)[len(*s)-1]
}
// Len gets the length of this stack
func (s *Stack) Len() int {
return len(*s)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment