Skip to content

225 use one queue #471

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Sep 13, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 12 additions & 5 deletions leetcode/stack/MyStack.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,24 +24,31 @@ type MyStack struct {

/** Initialize your data structure here. */
func MyStackConstructor() MyStack {
return MyStack{}
return MyStack{
q: []int{},
}
}

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

/** Removes the element on top of the stack and returns that element. */
func (this *MyStack) Pop() int {
r := this.q[len(this.q)-1]
this.q = this.q[:len(this.q)-1]
return r
top := this.q[0]
this.q = this.q[1:]
return top
}

/** Get the top element. */
func (this *MyStack) Top() int {
return this.q[len(this.q)-1]
return this.q[0]
}

/** Returns whether the stack is empty. */
Expand Down
Loading