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

  • 相关阅读:
    dropdownlist下拉框加--请选择---
    vs2012中自带IIS如何让其他电脑访问
    win7 web开发遇到的问题-由于权限不足而无法读取配置文件,无法访问请求的页面
    无法打开登录所请求的数据库 "xxxx"。登录失败。 用户 'NT AUTHORITYSYSTEM' 登录失败。
    如何实现删除确认
    如何获取GridView的总记录数?
    SQL两张表如何关联
    ES7学习笔记——Array.prototype.includes和求幂运算符**
    一些常用的JavaScript正则表达式
    Vue.js 2.x中事件总线(EvevntBus)及element-ui中全屏loading的使用
  • 原文地址:https://www.cnblogs.com/sherylwang/p/5595906.html
Copyright © 2011-2022 走看看