-
Notifications
You must be signed in to change notification settings - Fork 0
/
stack_list.go
61 lines (52 loc) · 1.17 KB
/
stack_list.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
package stack
// stackList represents a stack implementation
// using slice as container
type stackList struct {
Data []*int
Size int
}
// NewStack constructs and returns
// new pointer to stack
func NewStack() *stackList {
return new(stackList)
}
// Push adds element(s) to stack
func (s *stackList) Push(items ...int) {
for _, item := range items {
s.Data = append(s.Data, &item)
}
s.Size += len(items)
}
// Pop removes an element from stack
func (s *stackList) Pop() int {
v := s.Data[s.Size-1]
s.Data = s.Data[:s.Size-1]
s.Size -= 1
return *v
}
// Peek returns element at the top of stack,
// but does not remove element from stack.
func (s *stackList) Peek() int {
return *s.Data[s.Size-1]
}
// Clear removes all element from stack
// The size is also reset to zero
func (s *stackList) Clear() {
s.Data = s.Data[:0]
s.Size = 0
}
// Swap exchanges first two items on stack
func (s *stackList) Swap() {
i, j := s.Pop(), s.Pop()
s.Push(i)
s.Push(j)
}
// RotateRight rotates n items on the stack
// to the right.
func (s *stackList) RotateRight(n int) {
for i := 1; i < n; i++ {
c := s.Size - i
p := s.Size - i - 1
s.Data[c], s.Data[p] = s.Data[p], s.Data[c]
}
}