225. 用队列实现栈

用队列实现栈

解法一: 双队列

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
type MyStack struct {
queue1 *[]int

queue2 *[]int
}

func Constructor() MyStack {
return MyStack{
queue1: &[]int{},
queue2: &[]int{},
}
}

func (this *MyStack) Push(x int) {
queue1 := this.queue1
queue2 := this.queue2
*queue2 = append(*queue2, x)
if len(*queue1) > 0 {
*queue2 = append(*queue2, *queue1...)
*queue1 = []int{}
}
this.queue1, this.queue2 = this.queue2, this.queue1
}

func (this *MyStack) Pop() int {
queue1 := this.queue1
ans := (*queue1)[0]
(*queue1) = (*queue1)[1:]
return ans
}

func (this *MyStack) Top() int {
queue1 := this.queue1
return (*queue1)[0]
}

func (this *MyStack) Empty() bool {
queue1 := this.queue1
return len(*queue1) == 0
}

/**
* Your MyStack object will be instantiated and called as such:
* obj := Constructor();
* obj.Push(x);
* param_2 := obj.Pop();
* param_3 := obj.Top();
* param_4 := obj.Empty();
*/

解法二: 一个队列

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
type MyStack struct {
queue *[]int
}

func Constructor() MyStack {
return MyStack{
queue: &[]int{},
}
}

func (this *MyStack) Push(x int) {
queue := this.queue
n := len(*queue)
*queue = append(*queue, x)
for i := 0; i < n; i++ {
*queue = append(*queue, (*queue)[i])
}
*queue = (*queue)[n:]
}

func (this *MyStack) Pop() int {
queue := this.queue
ans := (*queue)[0]
(*queue) = (*queue)[1:]
return ans
}

func (this *MyStack) Top() int {
queue := this.queue
return (*queue)[0]
}

func (this *MyStack) Empty() bool {
queue := this.queue
return len(*queue) == 0
}

/**
* Your MyStack object will be instantiated and called as such:
* obj := Constructor();
* obj.Push(x);
* param_2 := obj.Pop();
* param_3 := obj.Top();
* param_4 := obj.Empty();
*/
作者

wuhunyu

发布于

2024-03-03

更新于

2025-01-15

许可协议