Skip to content

Commit 46d3907

Browse files
author
legolas.zhan
committed
232: impl queue using stacks
1 parent d563fe9 commit 46d3907

File tree

2 files changed

+34
-27
lines changed

2 files changed

+34
-27
lines changed

leetcode/stack/MyQueue.go

Lines changed: 21 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,8 @@ You may assume that all operations are valid (for example, no pop or peek operat
1616
package lstack
1717

1818
type MyQueue struct {
19-
q []int
19+
stack1 []int
20+
stack2 []int
2021
}
2122

2223
/** Initialize your data structure here. */
@@ -25,24 +26,32 @@ func MyQueueConstructor() MyQueue {
2526
}
2627

2728
/** Push element x to the back of queue. */
28-
func (this *MyQueue) Push(x int) {
29-
// 可以考虑两个 []int 提高push性能,代价是pop/peek 性能降低
30-
this.q = append([]int{x}, this.q...)
29+
func (m *MyQueue) Push(x int) {
30+
m.stack1 = append(m.stack1, x)
3131
}
3232

3333
/** Removes the element from in front of queue and returns that element. */
34-
func (this *MyQueue) Pop() int {
35-
r := this.q[len(this.q)-1]
36-
this.q = this.q[:len(this.q)-1]
37-
return r
34+
func (m *MyQueue) Pop() int {
35+
m.Peek()
36+
top := len(m.stack2) - 1
37+
value := m.stack2[len(m.stack2)-1]
38+
m.stack2 = m.stack2[:top]
39+
return value
3840
}
3941

4042
/** Get the front element. */
41-
func (this *MyQueue) Peek() int {
42-
return this.q[len(this.q)-1]
43+
func (m *MyQueue) Peek() int {
44+
if len(m.stack2) == 0 {
45+
for len(m.stack1) > 0 {
46+
top := len(m.stack1) - 1
47+
m.stack2 = append(m.stack2, m.stack1[top])
48+
m.stack1 = m.stack1[:top]
49+
}
50+
}
51+
return m.stack2[len(m.stack2)-1]
4352
}
4453

4554
/** Returns whether the queue is empty. */
46-
func (this *MyQueue) Empty() bool {
47-
return len(this.q) == 0
55+
func (m *MyQueue) Empty() bool {
56+
return len(m.stack1) == 0 && len(m.stack2) == 0
4857
}

leetcode/stack/MyQueue_test.go

Lines changed: 13 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,25 +1,23 @@
11
package lstack
22

3-
import "testing"
3+
import (
4+
"testing"
5+
6+
"github.com/stretchr/testify/assert"
7+
)
48

59
func Test_MyQueue(t *testing.T) {
10+
assert := assert.New(t)
11+
612
myqueue := MyQueueConstructor()
713
myqueue.Push(1)
814
myqueue.Push(2)
915
myqueue.Push(3)
1016

11-
if r := myqueue.Empty(); r != false {
12-
t.Fatal("Empty:", r)
13-
}
14-
15-
if r := myqueue.Peek(); r != 1 {
16-
t.Fatal("Peek:", r)
17-
}
18-
19-
myqueue.Pop()
20-
myqueue.Pop()
21-
myqueue.Pop()
22-
if r := myqueue.Empty(); r != true {
23-
t.Fatal("Empty:", r)
24-
}
17+
assert.False(myqueue.Empty())
18+
assert.Equal(1, myqueue.Peek())
19+
assert.Equal(1, myqueue.Pop())
20+
assert.Equal(2, myqueue.Pop())
21+
assert.Equal(3, myqueue.Pop())
22+
assert.True(myqueue.Empty())
2523
}

0 commit comments

Comments
 (0)