Implement Queue using Stacks

本文介绍了一种使用栈实现队列的方法,通过两个栈分别作为输入栈和输出栈,实现队列的push、pop、peek和empty操作。文章详细解释了如何在需要时将输入栈的元素逆序转移到输出栈,以支持队列的先进先出特性。
摘要由CSDN通过智能技术生成

mplement the following operations of a queue using stacks.

  • push(x) -- Push element x to the back of queue.
  • pop() -- Removes the element from in front of queue.
  • peek() -- Get the front element.
  • empty() -- Return whether the queue is empty.

Notes:

    • You must use only standard operations of a stack -- which means only push to top, peek/pop from top, size, and is empty operations are valid.
    • Depending on your language, stack may not be supported natively. You may simulate a stack by using a list or deque (double-ended queue), as long as you use only standard operations of a stack.
    • You may assume that all operations are valid (for example, no pop or peek operations will be called on an empty queue).

这是<剑指offer>上的一道题.与Implement Stack using Queues互为对偶.这里主要的难点不在添加元素,而在于如何利用从尾部pop的栈实现从头pop().使用栈没法像queue那样进行左旋,所以不可避免要使用两个stack,stack1为input栈,stack2为ouput栈.input栈负责增加元素,一旦要进行peek或者pop操作,output栈就要启用,如果为空的话,需要从input栈中逆序增加元素.因为queue先进先出,所以后来再加入stack1的元素,在stack2不为空的情况下,并不影响peek和pop操作.代码如下:

class Queue(object):
    def __init__(self):
        """
        initialize your data structure here.
        """
        self.stack1 = []
        self.stack2 = []
        
    def adjust(self):
        if not self.stack2:
            while self.stack1:
                self.stack2.append(self.stack1.pop())
                
    def push(self, x):
        """
        :type x: int
        :rtype: nothing
        """
        self.stack1.append(x)
        

    def pop(self):
        """
        :rtype: nothing
        """
        if not self.empty():
            self.stack2.pop()
        

    def peek(self):
        """
        :rtype: int
        """
        if not self.empty():
            return self.stack2[-1]
        

    def empty(self):
        """
        :rtype: bool
        """
        self.adjust()
        return len(self.stack2) == 0 

给出一个leetcode上的参考代码,和我的没有本质差别:

class Queue {
    stack<int> input, output;
public:

    void push(int x) {
        input.push(x);
    }

    void pop(void) {
        peek();
        output.pop();
    }

    int peek(void) {
        if (output.empty())
            while (input.size())
                output.push(input.top()), input.pop();
        return output.top();
    }

    bool empty(void) {
        return input.empty() && output.empty();
    }
};

 每个元素都会在stack1,stack2存储一次,所以所有操作的均摊复杂度都为O(1).

转载于:https://www.cnblogs.com/sherylwang/p/5595906.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值