232.用栈实现队列
主要是需要一步一步实现,难度倒是不难
type MyQueue struct {
instack, outstack []int
}
func Constructor() MyQueue {
return MyQueue{}
}
func (this *MyQueue) Push(x int) {
this.instack = append(this.instack, x)
}
func (this *MyQueue) in2out(){
for len(this.instack) > 0{
this.outstack = append(this.outstack, this.instack[len(this.instack) - 1])
this.instack = this.instack[:len(this.instack) - 1]
}
}
func (this *MyQueue) Pop() int {
if len(this.outstack) == 0{
this.in2out()
}
ret := this.outstack[len(this.outstack) - 1]
this.outstack = this.outstack[:len(this.outstack) - 1]
return ret
}
func (this *MyQueue) Peek() int {
if len(this.outstack) == 0{
this.in2out()
}
return this.outstack[len(this.outstack) - 1]
}
func (this *MyQueue) Empty() bool {
return len(this.instack) == 0 && len(this.outstack) == 0
}
225. 用队列实现栈
type MyStack struct {
queue []int
}
func Constructor() MyStack {
return MyStack{}
}
func (this *MyStack) Push(x int) {
this.queue = append(this.queue, x)
}
func (this *MyStack) Pop() int {
ret := this.queue[len(this.queue) - 1]
this.queue = this.queue[:len(this.queue) - 1]
return ret
}
func (this *MyStack) Top() int {
return this.queue[len(this.queue) - 1]
}
func (this *MyStack) Empty() bool {
return len(this.queue) == 0
}