-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstack.go
58 lines (48 loc) · 789 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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
package main
import "fmt"
type stack[T any] []T
func (s *stack[T]) push(elem T) {
*s = append(*s, elem)
}
func (s *stack[T]) pop() {
if len(*s) > 0 {
*s = (*s)[:len(*s)-1]
}
}
func (s *stack[T]) top() *T {
if len(*s) > 0 {
return &(*s)[len(*s)-1]
}
return nil
}
func (s *stack[T]) len() int {
return len(*s)
}
func (s *stack[T]) print() {
for _, elem := range *s {
fmt.Print(elem)
fmt.Print(" ")
}
fmt.Println("")
}
func main() {
ss := stack[string]{}
ss.push("Hello")
ss.push("Hao")
ss.push("Chen")
ss.print()
fmt.Printf("stack top is - %v\n", *(ss.top()))
ss.pop()
ss.pop()
ss.print()
ns := stack[int]{}
ns.push(10)
ns.push(20)
ns.print()
ns.pop()
ns.print()
*ns.top() += 1
ns.print()
ns.pop()
fmt.Printf("stack top is - %v\n", ns.top())
}