232. Implement Queue using Stacks [easy] (Python)

题目链接

https://leetcode.com/problems/implement-queue-using-stacks/

题目原文

Implement the following operations of a queue using stacks.

  1. push(x) – Push element x to the back of queue.
  2. pop() – Removes the element from in front of queue.
  3. peek() – Get the front element.
  4. empty() – Return whether the queue is empty.

Notes:

  1. 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.
  2. 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.
  3. You may assume that all operations are valid (for example, no pop or peek operations will be called on an empty queue).

题目翻译

太长不翻了。大概就是用栈的push to top, peek/pop from top, size, is empty方法,实现队列的push, pop, peek, empty方法。

思路方法

镜像问题:225. Implement Stack using Queues

这个题目的关键点在于,只能用栈的几个操作实现。
由于栈先进后出,和队列先进先出天然矛盾,故考虑采用两个栈,一个只进行入栈push操作,一个只进行出栈pop或peek操作。当只进行出栈操作的栈空时将另一个栈中的内容push到该栈,如此,就拥有了先进先出的特性。

代码

class Queue(object):
    def __init__(self):
        """
        initialize your data structure here.
        """
        self.inStack, self.outStack = [], []

    def push(self, x):
        """
        :type x: int
        :rtype: nothing
        """
        self.inStack.append(x)

    def pop(self):
        """
        :rtype: nothing
        """
        self.peek()
        self.outStack.pop()

    def peek(self):
        """
        :rtype: int
        """
        if not self.outStack:
            while self.inStack:
                self.outStack.append(self.inStack.pop())
        return self.outStack[-1]

    def empty(self):
        """
        :rtype: bool
        """
        return not self.inStack and not self.outStack

PS: 新手刷LeetCode,新手写博客,写错了或者写的不清楚还请帮忙指出,谢谢!
转载请注明:http://blog.csdn.net/coder_orz/article/details/51586814

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值