[LeetCode] 232. Implement Queue using Stacks_Easy tag: stack

Posted johnsonxiong

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[LeetCode] 232. Implement Queue using Stacks_Easy tag: stack相关的知识,希望对你有一定的参考价值。

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

Example:

MyQueue queue = new MyQueue();

queue.push(1);
queue.push(2);  
queue.peek();  // returns 1
queue.pop();   // returns 1
queue.empty(); // returns false

Notes:

  • You must use only standard operations of a stack -- which means only push to toppeek/pop from topsize, 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).

 

这个题目就是利用两个stack,一个来存放顺序的stack,另外一个存放逆序的stack(也就是正序的queue),如果queue为空的时候要pop(),那么就将stack中的全部移到queue中。

Note:时间复杂度在这里不是看的最坏时间复杂度,而是average 时间复杂度,虽然一次pop的最坏情况可能是 O(n), 但是平均的时间是O(1). 

tips:看每一步时间复杂度时不太明确的时候,可以看每一个data,比如这个两个stack中的每个num,最多会进出stack一次,进出queue一次,共4次,是O(1) 的时间复杂度, 所以每次操作就是O(1) 的时间复杂度。

Code

class MyQueue:
    def __init__(self):
        self.stack = []
        self.queue = []
    def push(self, x) -> None:
        self.stack.append(x)
    def pop(self) -> int:
        if not self.queue:
            while self.stack:
                self.queue.append(self.stack.pop())
        if self.queue:
            return self.queue.pop()
    def peek(self) -> int:
        return self.queue[-1] if self.queue else self.stack[0]
    def empty(self) -> bool:
        return not self.queue and not self.stack

 

以上是关于[LeetCode] 232. Implement Queue using Stacks_Easy tag: stack的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode 232: Implement Queue using Stacks

[Leetcode] 232. Implement Queue using Stacks

leetcode 232. Implement Queue using Stacks

LeetCode 232 Implement Queue using Stacks

LeetCode OJ 232Implement Queue using Stacks

LeetCode 232. Implement Queue using Stacks