用栈实现队列-栈与队列232-python

没看答案。

利用两个栈

python

class MyQueue:
    def __init__(self):
        self.stack1 = []
        self.stack2 = []

    def push(self, x: int) -> None:
        if not self.stack1:
            self.stack1.append(x)
        else:
            self.stack2.append(x)

    def pop(self) -> int:
        x = self.stack1.pop()
        if not self.stack1:
            while self.stack2:
                self.stack1.append(self.stack2.pop())
        return x

    def peek(self) -> int:
        return self.stack1[-1]

    def empty(self) -> bool:
        return False if self.stack1 else True

# Your MyQueue object will be instantiated and called as such:
# obj = MyQueue()
# obj.push(x)
# param_2 = obj.pop()
# param_3 = obj.peek()
# param_4 = obj.empty()

C++
(剑指offer09)

class CQueue {
private:
    stack<int> stk1;
    stack<int> stk2;
public:
    void appendTail(int value) {
        if(stk1.empty()){
            stk1.push(value);
        }else{
            while(!stk1.empty()){
                int temp1 = stk1.top();
                stk1.pop();
                stk2.push(temp1);
            }
            stk1.push(value);
            while(!stk2.empty()){
                int temp2 = stk2.top();
                stk2.pop();
                stk1.push(temp2);
            }
        }
    }
    
    int deleteHead() {
        if(stk1.empty()) return -1;
        int temp3 = stk1.top();
        stk1.pop();
        return temp3;
    }
};

/**
 * Your CQueue object will be instantiated and called as such:
 * CQueue* obj = new CQueue();
 * obj->appendTail(value);
 * int param_2 = obj->deleteHead();
 */

利用一个栈

python

class MyQueue:

    def __init__(self):
        self.stack = list()
        self.length = 0

    def push(self, x: int) -> None:
        self.stack.append(x)
        self.length += 1

    def pop(self) -> int:
        num = self.stack.pop(0)
        self.length -= 1
        return num

    def peek(self) -> int:
        num = self.stack[0]
        return num

    def empty(self) -> bool:
        return True if self.length == 0 else False


# Your MyQueue object will be instantiated and called as such:
# obj = MyQueue()
# obj.push(x)
# param_2 = obj.pop()
# param_3 = obj.peek()
# param_4 = obj.empty()
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值