-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStack.go
More file actions
78 lines (68 loc) · 1.44 KB
/
Stack.go
File metadata and controls
78 lines (68 loc) · 1.44 KB
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
77
78
package stack
import (
"container/list"
"errors"
)
//Stack represents the LIFO data structure.
type Stack struct {
stack *list.List
}
//Constructor for Stack.
//If params is empty, it will new a empty Stack.
//Or you can pass a List to initialize the Stack.
func New(params ...*list.List) (*Stack, error) {
sta := new(Stack)
var err error = nil
switch len(params) {
case 0:
sta.stack = list.New()
case 1:
sta.stack = params[0]
default:
err = errors.New("The parameter is incorrect")
}
return sta, err
}
//Get the Stack size.
func (sta *Stack) Size() int {
return sta.stack.Len()
}
//Check whether the Stack is empty or not.
func (sta *Stack) Empty() bool {
return sta.stack.Len() == 0
}
//Insert the value above the top.
func (sta *Stack) Push(val interface{}) {
sta.stack.PushBack(val)
}
//Delete the top value in Stack.
//If the Stack is empty, it will do nothing.
func (sta *Stack) Pop() {
if !sta.Empty() {
sta.stack.Remove(sta.stack.Back())
}
}
//Get the top value in Stack.
//If the Stack is empty, you will get nil.
func (sta *Stack) Top() interface{} {
if sta.Empty() {
return nil
} else {
return sta.stack.Back().Value
}
}
//Reverse the contents in the Stack.
func (sta *Stack) Reverse() {
tmp := list.New()
for !sta.Empty() {
tmp.PushBack(sta.Top())
sta.Pop()
}
sta.stack = tmp
}
//Swap the contents of two Stacks.
func (sta1 *Stack) Swap(sta2 *Stack) {
tmp := sta1.stack
sta1.stack = sta2.stack
sta2.stack = tmp
}