-
Notifications
You must be signed in to change notification settings - Fork 19
/
Copy pathstack.go
49 lines (41 loc) · 799 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
package main
import (
"fmt"
)
type Node struct {
Value int
}
/*
func (n *Node) String() string {
return fmt.Sprint(n.Value)
}
*/
// NewStack returns a new stack.
func NewStack() *Stack {
return &Stack{}
}
// Stack is a basic LIFO stack that resizes as needed.
type Stack struct {
nodes []*Node
count int
}
// Push adds a node to the stack.
func (s *Stack) Push(n *Node) {
s.nodes = append(s.nodes[:s.count], n)
s.count++
}
// Pop removes and returns a node from the stack in last to first order.
func (s *Stack) Pop() *Node {
if s.count == 0 {
return nil
}
s.count--
return s.nodes[s.count]
}
func main() {
s := NewStack()
s.Push(&Node{1})
s.Push(&Node{2})
s.Push(&Node{3})
fmt.Println(s.Pop(), s.Pop(), s.Pop())
}