-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathstack-linked.go
59 lines (46 loc) · 980 Bytes
/
stack-linked.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
package main
import "fmt"
func UseLinkedStack() {
stack := NewLinkedStack()
stack.Push(1)
stack.Push(2)
fmt.Println(stack.Peek())
fmt.Println(stack.Pop())
fmt.Println(stack.Peek())
stack.Push("String")
fmt.Println(stack.Size())
fmt.Println(stack.Peek())
fmt.Println(stack.Pop())
fmt.Println(stack.Peek())
}
type LinkedStack struct {
linkedList LinkedList
}
func NewLinkedStack() LinkedStack {
return LinkedStack{linkedList: LinkedList{
count: 0,
head: nil,
tail: nil,
}}
}
func (ls *LinkedStack) Peek() interface{} {
if ls.IsEmpty() {
return nil
}
return ls.linkedList.head.value
}
func (ls *LinkedStack) Push(value interface{}) {
ls.linkedList.PreAdd(value)
}
func (ls *LinkedStack) Pop() interface{} {
if ok, removed := ls.linkedList.RemoveHead(); ok {
return removed.value
}
return nil
}
func (ls *LinkedStack) IsEmpty() bool {
return ls.linkedList.head == nil
}
func (ls *LinkedStack) Size() int {
return ls.linkedList.Size()
}