码迷,mamicode.com
首页 > 其他好文 > 详细

[LC] 225. Implement Stack using Queues

时间:2019-11-02 12:00:10      阅读:65      评论:0      收藏:0      [点我收藏+]

标签:span   led   style   ati   get   ack   bsp   from   tac   

Implement the following operations of a 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.

Example:

MyStack stack = new MyStack();

stack.push(1);
stack.push(2);  
stack.top();   // returns 2
stack.pop();   // returns 2
stack.empty(); // returns false

class MyStack:
    
    def __init__(self):
        """
        Initialize your data structure here.
        """
        from collections import deque
        self.queue = deque()

    def push(self, x: int) -> None:
        """
        Push element x onto stack.
        """
        self.queue.append(x)
        for i in range(len(self.queue) - 1):
            self.queue.append(self.queue.popleft())
        

    def pop(self) -> int:
        """
        Removes the element on top of the stack and returns that element.
        """
        return self.queue.popleft()

    def top(self) -> int:
        """
        Get the top element.
        """
        return self.queue[0]

    def empty(self) -> bool:
        """
        Returns whether the stack is empty.
        """
        return not self.queue


# Your MyStack object will be instantiated and called as such:
# obj = MyStack()
# obj.push(x)
# param_2 = obj.pop()
# param_3 = obj.top()
# param_4 = obj.empty()

 

[LC] 225. Implement Stack using Queues

标签:span   led   style   ati   get   ack   bsp   from   tac   

原文地址:https://www.cnblogs.com/xuanlu/p/11781045.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!