Stack
Example
package collatz
type Stack struct {
data []int
}
func NewStack(cap int) *Stack {
if cap < 1 {
cap = 1024
}
return &Stack{
data: make([]int, 0, cap),
}
}
func (s *Stack) push(x int) {
s.data = append(s.data, x)
}
func (s *Stack) pop() int {
if len(s.data) < 1 {
return -1
}
v := s.data[len(s.data)-1]
s.data = s.data[:len(s.data)-1]
return v
}
func (s *Stack) empty() bool {
return len(s.data) < 1
}
type Stack struct {
data []int
}
func NewStack(cap int) *Stack {
if cap < 1 {
cap = 1024
}
return &Stack{
data: make([]int, 0, cap),
}
}
func (s *Stack) push(x int) {
s.data = append(s.data, x)
}
func (s *Stack) pop() int {
if len(s.data) < 1 {
return -1
}
v := s.data[len(s.data)-1]
s.data = s.data[:len(s.data)-1]
return v
}
func (s *Stack) empty() bool {
return len(s.data) < 1
}
Generic Example
package collections
type Stack struct {
items []TempDate
}
func NewStack() *Stack {
return &Stack{
items: make([]TempDate, 0, 3),
}
}
func (s *Stack) Push(x TempDate) {
s.items = append(s.items, x)
}
func (s *Stack) Pop() TempDate {
x := s.items[len(s.items)-1]
s.items = s.items[:len(s.items)-1]
return x
}
func (s *Stack) Peek() TempDate {
return s.items[len(s.items)-1]
}
func (s *Stack) Empty() bool {
return len(s.items) < 1
}
type Stack struct {
items []TempDate
}
func NewStack() *Stack {
return &Stack{
items: make([]TempDate, 0, 3),
}
}
func (s *Stack) Push(x TempDate) {
s.items = append(s.items, x)
}
func (s *Stack) Pop() TempDate {
x := s.items[len(s.items)-1]
s.items = s.items[:len(s.items)-1]
return x
}
func (s *Stack) Peek() TempDate {
return s.items[len(s.items)-1]
}
func (s *Stack) Empty() bool {
return len(s.items) < 1
}