• Implement Queue using Stacks


    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).

  • 相关阅读:
    安卓学习26(ListView的焦点问题)
    ACL Contest1 B- Sum is Multiple 数论,EXGCD
    P4137 Rmq Problem / mex 可持久化线段树求区间MEX
    [可持久化权值线段树] [模板] [数组版本]
    CodeForces383C Propagating tree 思维 线段树 DFS序
    CodeForces 558E A Simple Task 线段树 桶排思想
    P1471 方差 线段树维护区间方差
    Leetcode1521 找到最接近目标的函数值 位运算
    CodeForces-739C Alyona and towers 线段树经典套路之维护左中右
    GYM-101194F Mr. Panda and Fantastic Beasts 后缀数组套路
  • 原文地址:https://www.cnblogs.com/sherylwang/p/5595906.html
Copyright © 2020-2023  润新知