232.用栈实现队列
题目链接/文章讲解/视频讲解:https://programmercarl.com/0232.%E7%94%A8%E6%A0%88%E5%AE%9E%E7%8E%B0%E9%98%9F%E5%88%97.html
type MyQueue struct {
stackIn []int
stackOut []int
}
func Constructor() MyQueue {
return MyQueue{
stackIn: make([]int, 0),
stackOut: make([]int, 0),
}
}
func (this *MyQueue) Push(x int) {
this.stackIn = append(this.stackIn,x)
}
func (this *MyQueue) Pop() int {
inLen,outLen := len(this.stackIn),len(this.stackOut)
if outLen == 0{
if inLen ==0{
return -1
}
for i := inLen-1; i >=0; i-- {
this.stackOut = append(this.stackOut,this.stackIn[i])
}
this.stackIn = []int{}
outLen = len(this.stackOut)
}
val := this.stackOut[outLen-1]
this.stackOut = this.stackOut[:outLen-1]
return val
}
func (this *MyQueue) Peek() int {
val:=this.Pop()
if val == -1{
return -1
}
this.stackOut = append(this.stackOut,val)
return val
}
func (this *MyQueue) Empty() bool {
return len(this.stackOut)==0&&len(this.stackIn)==0
}
225. 用队列实现栈
题目链接/文章讲解/视频讲解:> https://programmercarl.com/0225.%E7%94%A8%E9%98%9F%E5%88%97%E5%AE%9E%E7%8E%B0%E6%A0%88.html
type MyStack struct {
queue []int
}
func Constructor() MyStack {
return MyStack{
queue:make([]int,0),
}
}
func (this *MyStack) Push(x int) {
this.queue = append(this.queue,x)
}
func (this *MyStack) Pop() int {
n:=len(this.queue)-1
for n!=0{
val :=this.queue[0]
this.queue = this.queue[1:]
this.queue = append(this.queue,val)
n--
}
val :=this.queue[0]
this.queue = this.queue[1:]
return val
}
func (this *MyStack) Top() int {
val:=this.Pop()
this.queue = append(this.queue,val)
return val
}
func (this *MyStack) Empty() bool {
return len(this.queue)==0
}
总结
用栈实现队列和 用队列实现栈 都要遵循队列和栈的特性,比如要队列实现栈 那么我的队列就要从尾部出