-
Notifications
You must be signed in to change notification settings - Fork 255
/
stack.go
37 lines (31 loc) · 590 Bytes
/
stack.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
package main
import "fmt"
// A simple stack using generics
type Stack[T any] struct {
items []T
}
func (stack *Stack[T]) Push(value T) {
stack.items = append(stack.items, value)
}
func (stack *Stack[T]) Pop() T {
n := len(stack.items)
if n <= 0 {
panic("Cannot pop an empty stack!")
}
value := stack.items[n-1]
stack.items = stack.items[:n-1]
return value
}
func (stack *Stack[T]) Show() {
fmt.Printf("%v\n", stack.items)
}
func main() {
pilha := Stack[int]{}
pilha.Push(1)
pilha.Push(2)
pilha.Push(3)
pilha.Push(4)
pilha.Pop()
fmt.Printf("Stack: ")
pilha.Show()
}