232. Implement Queue using Stack

2016-07-11  本文已影响7人  codingXue

问题描述

Implement the following operations of a queue using stacks.

Notes:

问题分析

这是一道Easy题,但是我并没有看懂题意……也是有一种每天蠢出新境界的感觉。参考:csdn-哈哈的个人专栏
思路是准备a、b两个栈,a负责入栈,b负责出栈。

AC代码

class Queue(object):
    def __init__(self):
        """
        initialize your data structure here.
        """
        self.a = []
        self.b = [] 

    def push(self, x):
        """
        :type x: int
        :rtype: nothing
        """
        self.a.append(x)
        
    def pop(self):
        """
        :rtype: nothing
        """
        if len(self.b) != 0: 
            return self.b.pop()
        else:
            while len(self.a) != 0:
                self.b.append(self.a.pop())
            return self.b.pop()  

    def peek(self):
        """
        :rtype: int
        """
        if len(self.b) != 0: 
            return self.b[-1]
        else:
            while len(self.a) != 0:
                self.b.append(self.a.pop())
            return self.b[-1]

    def empty(self):
        """
        :rtype: bool
        """
        return len(self.a) == 0 and len(self.b) == 0

Runtime: 44 ms, which beats 71.08% of Python submissions.

上一篇下一篇

猜你喜欢

热点阅读