-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstack.go
76 lines (61 loc) · 1.11 KB
/
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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
package gods
import (
"fmt"
)
// Stack using linked list
type Stack struct {
Top *Node
Length int
}
// Node that has link of previous node
type Node struct {
Value interface{}
Prev *Node
}
// NewStack : constructor for new stack
func NewStack() *Stack {
return &Stack{nil, 0}
}
// Add addes element on stacks
func (s *Stack)Add(items ...interface{}) {
for _, i := range items {
n := Node{Value: i, Prev: s.Top}
s.Top = &n
s.Length++
}
}
// Pop removes top element from stack
func (s *Stack)Pop() interface{} {
if s.Length == 0 {
return nil
}
t := s.Top
s.Top = t.Prev
s.Length--
return t.Value
}
// Peek return top element from Stack
func (s *Stack) Peek() interface{} {
if s.Length == 0 {
return nil
}
return s.Top.Value
}
// Len return lenght of stack
func (s *Stack) Len() int {
return s.Length
}
// Push inserts a element from stack
func (s *Stack) Push(item interface{}) {
n := &Node{Value: item, Prev: s.Top}
s.Top = n
s.Length++
}
// Print prints all the elements from stack
func (s *Stack) Print() {
top := s.Top
for top != nil {
fmt.Println(top.Value)
top = top.Prev
}
}