forked from kelvins/algorithms-and-data-structures
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstack.go
More file actions
37 lines (31 loc) · 590 Bytes
/
stack.go
File metadata and controls
37 lines (31 loc) · 590 Bytes
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() {
stack := Stack[int]{}
stack.Push(1)
stack.Push(2)
stack.Push(3)
stack.Push(4)
stack.Pop()
fmt.Printf("Stack: ")
stack.Show()
}