20170630-leetcode-225 Implement Stack using Queues

1.Description

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.
Notes:
You must use only standard operations of a queue – which means only push to back, peek/pop from front, size, and is empty operations are valid.
Depending on your language, queue may not be supported natively. You may simulate a queue by using a list or deque (double-ended queue), as long as you use only standard operations of a queue.
You may assume that all operations are valid (for example, no pop or top operations will be called on an empty stack).
解讀:用棧實現隊列,在Python裏面可以考慮使用deque

2.Solution

思路:使用雙向隊列dequeue
壓棧:
1)使用另外的變量存儲要壓棧的數據,然後把原來的隊列extend後面
2)只使用數據本身的隊列,首先把壓棧的數據append原來的隊列,然後遍歷前面n-1個數據,popleft同時append到這個隊列中後面
彈出:雙向隊列popleft
top():取出雙向隊列的第一個元素

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

    def push(self, x):
        """
        Push element x onto stack.
        :type x: int
        :rtype: void
        """
        q=self._queue
        q.append(x)#把x加入到列表中
        for _ in range(len(q)-1):#把要添加的元素之前
            q.append(q.popleft())

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

    def top(self):
        """
        Get the top element.
        :rtype: int
        """
        return self._queue[0]

    def empty(self):
        """
        Returns whether the stack is empty.
        :rtype: bool
        """
        return not len(self._queue)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章