Skip to content

Commit d563fe9

Browse files
authored
Merge pull request #471 from TTWShell/bugfix/225
225 use one queue
2 parents adc716b + 2138e54 commit d563fe9

File tree

1 file changed

+12
-5
lines changed

1 file changed

+12
-5
lines changed

leetcode/stack/MyStack.go

Lines changed: 12 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -24,24 +24,31 @@ type MyStack struct {
2424

2525
/** Initialize your data structure here. */
2626
func MyStackConstructor() MyStack {
27-
return MyStack{}
27+
return MyStack{
28+
q: []int{},
29+
}
2830
}
2931

3032
/** Push element x onto stack. */
3133
func (this *MyStack) Push(x int) {
3234
this.q = append(this.q, x)
35+
// 将前面所有元素轮转到队列尾部
36+
for i := 0; i < len(this.q)-1; i++ {
37+
this.q = append(this.q, this.q[0])
38+
this.q = this.q[1:]
39+
}
3340
}
3441

3542
/** Removes the element on top of the stack and returns that element. */
3643
func (this *MyStack) Pop() int {
37-
r := this.q[len(this.q)-1]
38-
this.q = this.q[:len(this.q)-1]
39-
return r
44+
top := this.q[0]
45+
this.q = this.q[1:]
46+
return top
4047
}
4148

4249
/** Get the top element. */
4350
func (this *MyStack) Top() int {
44-
return this.q[len(this.q)-1]
51+
return this.q[0]
4552
}
4653

4754
/** Returns whether the stack is empty. */

0 commit comments

Comments
 (0)