-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlinked_stack.go
More file actions
64 lines (52 loc) · 1.2 KB
/
Copy pathlinked_stack.go
File metadata and controls
64 lines (52 loc) · 1.2 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
package stack
import (
"fmt"
"strings"
ll "go-algorithms/data_structures/linkedlist"
)
// LinkedListStack 使用链表实现栈
//
// 使用链表头作为栈顶
// 示意图为 Top(Head) [ 1, 3, 5 ...] Bottom(Tail)
type LinkedListStack struct {
items *ll.SingleLinkedList
}
// NewLinkedStack 返回一个新的单链表实现的空栈
func NewLinkedStack() *LinkedListStack {
return &LinkedListStack{
items: ll.NewSll(),
}
}
func (s *LinkedListStack) Push(data interface{}) {
s.items.Add(data)
}
func (s *LinkedListStack) Pop() interface{} {
if s.IsEmpty() {
panic("Can't pop from empty stack.")
}
return s.items.Remove(0)
}
func (s *LinkedListStack) Peek() interface{} {
if s.IsEmpty() {
panic("Can't peek from empty stack.")
}
return s.items.Get(0)
}
func (s *LinkedListStack) IsEmpty() bool {
return s.items.IsEmpty()
}
func (s *LinkedListStack) Size() int {
return s.items.Size()
}
func (s *LinkedListStack) String() string {
var builder strings.Builder
builder.WriteString("Top [ ")
for i, item := range s.items.Values() {
builder.WriteString(fmt.Sprint(item))
if i != s.items.Size()-1 {
builder.WriteString(", ")
}
}
builder.WriteString(" ] Bottom")
return builder.String()
}