Golang | Leetcode Golang题解之第232题用栈实现队列

07-19 1009阅读

题目:

Golang | Leetcode Golang题解之第232题用栈实现队列

题解:

type MyQueue struct {
    inStack, outStack []int
}
func Constructor() MyQueue {
    return MyQueue{}
}
func (q *MyQueue) Push(x int) {
    q.inStack = append(q.inStack, x)
}
func (q *MyQueue) in2out() {
    for len(q.inStack) > 0 {
        q.outStack = append(q.outStack, q.inStack[len(q.inStack)-1])
        q.inStack = q.inStack[:len(q.inStack)-1]
    }
}
func (q *MyQueue) Pop() int {
    if len(q.outStack) == 0 {
        q.in2out()
    }
    x := q.outStack[len(q.outStack)-1]
    q.outStack = q.outStack[:len(q.outStack)-1]
    return x
}
func (q *MyQueue) Peek() int {
    if len(q.outStack) == 0 {
        q.in2out()
    }
    return q.outStack[len(q.outStack)-1]
}
func (q *MyQueue) Empty() bool {
    return len(q.inStack) == 0 && len(q.outStack) == 0
}
VPS购买请点击我

文章版权声明:除非注明,否则均为主机测评原创文章,转载或复制请以超链接形式并注明出处。

目录[+]