- Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path225.myStack.go
59 lines (49 loc) · 1.11 KB
/
225.myStack.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 mystack
import (
_ "fmt"
"Leetcode/algorithms/kit"
)
// MyStack Declare
typeMyStackstruct {
queue*Queue
}
// NewMyStack Constructor
funcNewMyStack() *MyStack {
return&MyStack{
queue: kit.NewQueue(),
}
}
// 思路:先将目标值入队列,再将目标值前面的n-1个数输出再依次压进入队尾
// 时间复杂度:O(n) 空间复杂度:O(1)
// Push element x onto stack
func (s*MyStack) Push(xint) {
// fmt.Printf("before push:%v\n", s.queue.PeekAll())
s.queue.Push(x)
// 从0到n-1元素
fori:=0; i<s.queue.Len()-1; i++ {
top:=s.queue.Peek() // 队头元素
s.queue.Pop()
s.queue.Push(top)
}
// fmt.Printf("after push:%v\n", s.queue.PeekAll())
}
// Pop Removes the element on top of the stack and returns that element
func (s*MyStack) Pop() int {
ifs.queue.IsEmpty() {
returnNULL
}
top:=s.queue.Peek()
s.queue.Pop()
returntop
}
// Top Get the top element
func (s*MyStack) Top() int {
ifs.queue.IsEmpty() {
returnNULL
}
returns.queue.Peek()
}
// Empty Returns whether the stack is empty
func (s*MyStack) Empty() bool {
returns.queue.IsEmpty()
}