@@ -16,7 +16,8 @@ You may assume that all operations are valid (for example, no pop or peek operat
1616package lstack
1717
1818type 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}
0 commit comments