zoukankan      html  css  js  c++  java
  • Implement Stack using Queues

    这题是使用队列去实现栈,属于比较基础的题目。需要考虑的点在于队列为先进先出,即入队在队尾,但是出队在队首,而栈为先进后出,即出栈和入栈都在栈尾。需要实现的功能如下:

    push(x) -- Push element x onto stack.

    pop() -- Removes the element on top of the stack.

    top() -- Get the top element.

    empty() -- Return whether the stack is empty.

    我的解法一,python使用collections.deque()

    class Stack(object):
        def __init__(self):
            """
            initialize your data structure here.
            """
            self.queue = collections.deque()
            
    
        def push(self, x):
            """
            :type x: int
            :rtype: nothing
            """
            self.queue.append(x)
    
        def pop(self):
            """
            :rtype: nothing
            """
            i = len(self.queue)-1
            while i > 0:
                self.queue.append(self.queue.popleft())
                i-=1
            self.queue.popleft()
                
    
        def top(self):
            """
            :rtype: int
            """
            size=len(self.queue)
            return self.queue[size-1]
            
    
        def empty(self):
            """
            :rtype: bool
            """
            return len(self.queue)==0
            

    这种解法其中push复杂度为O(1),pop,top,empty复杂度都为为O(n),属于比较不理想的解法。

    参考一些优质解法,一个非常巧妙的思路逆序存储。具体做法为:在push元素之后,对queue中已有的元素做一个queue长度n-1次的右旋转, 相当于rotate(len(queue)-1),相当于将该元素插入在了队首。而从一开始push()就如此操作,相当于每次push之后,queue中的元素都保持原有的元素的逆序。从而使pop和top操作都为O(1),只有empty和push操作都为O(n).代码如下:

    class Stack(object):
        def __init__(self):
            """
            initialize your data structure here.
            """
            self.queue = collections.deque()
            
    
        def push(self, x):
            """
            :type x: int
            :rtype: nothing
            """
            self.queue.append(x)
            i=len(self.queue)-1
            while i > 0:
                self.queue.append(self.queue.popleft())
                i-=1
    
        def pop(self):
            """
            :rtype: nothing
            """
            self.queue.popleft()
                
    
        def top(self):
            """
            :rtype: int
            """
            return self.queue[0]
            
    
        def empty(self):
            """
            :rtype: bool
            """
            return len(self.queue)==0
  • 相关阅读:
    Java基础知识(一)环境变量的设置、变量与常量、自动类型转换、自增长、赋值运算符
    ModelState
    DOM
    正则表达式常见形式
    通过JS设置一个元素的文本
    JS(三) 原型对象与原型链
    JS(二)call方法和apply方法
    第四周学习进度表
    敏捷开发方法综述
    数组02
  • 原文地址:https://www.cnblogs.com/sherylwang/p/5373017.html
Copyright © 2011-2022 走看看