zoukankan      html  css  js  c++  java
  • 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).

  • 相关阅读:
    Open source cryptocurrency exchange
    Salted Password Hashing
    95. Unique Binary Search Trees II
    714. Best Time to Buy and Sell Stock with Transaction Fee
    680. Valid Palindrome II
    Java compiler level does not match the version of the installed Java project facet.
    eclipse自动编译
    Exception in thread "main" java.lang.StackOverflowError(栈溢出)
    博客背景美化——动态雪花飘落
    java九九乘法表
  • 原文地址:https://www.cnblogs.com/sherylwang/p/5595906.html
Copyright © 2011-2022 走看看