列表

详情


剑指 Offer 09. 用两个栈实现队列

用两个栈实现一个队列。队列的声明如下,请实现它的两个函数 appendTaildeleteHead ,分别完成在队列尾部插入整数和在队列头部删除整数的功能。(若队列中没有元素,deleteHead 操作返回 -1 )

 

示例 1:

输入:
["CQueue","appendTail","deleteHead","deleteHead"]
[[],[3],[],[]]
输出:[null,null,3,-1]

示例 2:

输入:
["CQueue","deleteHead","appendTail","appendTail","deleteHead","deleteHead"]
[[],[],[5],[2],[],[]]
输出:[null,-1,null,null,5,2]

提示:

原站题解

去查看

上次编辑到这里,代码来自缓存 点击恢复默认模板
class CQueue { public: CQueue() { } void appendTail(int value) { } int deleteHead() { } }; /** * Your CQueue object will be instantiated and called as such: * CQueue* obj = new CQueue(); * obj->appendTail(value); * int param_2 = obj->deleteHead(); */

golang 解法, 执行用时: 160 ms, 内存消耗: 8 MB, 提交时间: 2022-08-25 15:28:42

type CQueue struct {
    inStack, outStack []int
}

func Constructor() CQueue {
    return CQueue{}
}

func (this *CQueue) AppendTail(value int)  {
    this.inStack = append(this.inStack, value)
}

func (this *CQueue) DeleteHead() int {
    if len(this.outStack) == 0 {
        if len(this.inStack) == 0 {
            return -1
        }
        this.in2out()
    }
    value := this.outStack[len(this.outStack)-1]
    this.outStack = this.outStack[:len(this.outStack)-1]
    return value
}

func (this *CQueue) 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]
    }
}


/**
 * Your CQueue object will be instantiated and called as such:
 * obj := Constructor();
 * obj.AppendTail(value);
 * param_2 := obj.DeleteHead();
 */

python3 解法, 执行用时: 372 ms, 内存消耗: 19.2 MB, 提交时间: 2022-08-25 15:27:29

class CQueue:

    def __init__(self):
        self.q = []

    def appendTail(self, value: int) -> None:
        self.q.append(value)


    def deleteHead(self) -> int:
        if len(self.q) == 0: return -1
        t = self.q[0]
        self.q = self.q[1:]
        return t


# Your CQueue object will be instantiated and called as such:
# obj = CQueue()
# obj.appendTail(value)
# param_2 = obj.deleteHead()

golang 解法, 执行用时: 292 ms, 内存消耗: 8.6 MB, 提交时间: 2021-06-10 20:53:28

type CQueue struct {
    q []int
}


func Constructor() CQueue {
    return CQueue{
        q: []int{},
    }
}


func (this *CQueue) AppendTail(value int)  {
    this.q = append(this.q, value)
}


func (this *CQueue) DeleteHead() int {
    if len(this.q) == 0 {
        return -1
    }
    t := this.q[0]
    this.q = this.q[1:]
    return t
}


/**
 * Your CQueue object will be instantiated and called as such:
 * obj := Constructor();
 * obj.AppendTail(value);
 * param_2 := obj.DeleteHead();
 */

上一题