| 1 |
package stack |
| 2 |
|
| 3 |
type ( |
| 4 |
Stack struct { |
| 5 |
top *node |
| 6 |
length int |
| 7 |
} |
| 8 |
node struct { |
| 9 |
value interface{} |
| 10 |
prev *node |
| 11 |
} |
| 12 |
) |
| 13 |
|
| 14 |
func New() *Stack { |
| 15 |
return &Stack{nil,0} |
| 16 |
} |
| 17 |
|
| 18 |
func (this *Stack) Len() int { |
| 19 |
return this.length |
| 20 |
} |
| 21 |
|
| 22 |
func (this *Stack) Peek() interface{} { |
| 23 |
if this.length == 0 { |
| 24 |
return nil |
| 25 |
} |
| 26 |
return this.top.value |
| 27 |
} |
| 28 |
|
| 29 |
func (this *Stack) Pop() interface{} { |
| 30 |
if this.length == 0 { |
| 31 |
return nil |
| 32 |
} |
| 33 |
|
| 34 |
n := this.top |
| 35 |
this.top = n.prev |
| 36 |
this.length-- |
| 37 |
return n.value |
| 38 |
} |
| 39 |
|
| 40 |
func (this *Stack) Push(value interface{}) { |
| 41 |
n := &node{value,this.top} |
| 42 |
this.top = n |
| 43 |
this.length++ |
| 44 |
} |