Leetcode刷題日記-程序員面試經典(2020.6.23):化棧爲隊

題目描述:

 

 思路整理:

此題爲簡單題,沒啥說的,我們直接用兩個棧,一個輸入棧,一個輸出棧即可來實現

代碼:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
# @Time : 2020/6/24 9:20 

# @Author : ZFJ

# @File : 化棧爲隊.py 

# @Software: PyCharm
"""


class MyQueue(object):
    """
    方法還是很簡單,我們使用兩個列表來模型入棧和出棧即可
    """

    def __init__(self):
        """
        Initialize your data structure here.
        """
        # 定義輸入棧和輸出棧
        self.pushs = []
        self.pops = []

    def push(self, x):
        """
        Push element x to the back of queue.
        :type x: int
        :rtype: None
        """
        # 實現入隊列
        self.pushs.append(x)

    def pop(self):
        """
        Removes the element from in front of queue and returns that element.
        :rtype: int
        """
        # 輸出隊列
        # 遇到現在輸出棧爲空
        if len(self.pops) == 0:
            # 將輸入棧元素添加到輸出棧
            for i in range(len(self.pushs)):
                # 調用pop()操作即可將先進後出轉換成先進先出
                self.pops.append(self.pushs.pop())
        return self.pops.pop()

    def peek(self):
        """
        Get the front element.
        :rtype: int
        """
        # 現在輸出棧爲空
        if len(self.pops) == 0:
            for i in range(len(self.pushs)):
                self.pops.append(self.pushs.pop())
        # 因爲peek()操作只是查看元素,不會移除元素,因此還要再次添加到棧中
        temp = self.pops.pop()
        self.pops.append(temp)
        return temp

    def empty(self):
        """
        Returns whether the queue is empty.
        :rtype: bool
        """
        # 只有輸入棧和輸出棧都爲空,才能判斷隊列爲空
        if len(self.pushs) == 0 and len(self.pops) == 0:
            return True
        else:
            return False


# Your MyQueue object will be instantiated and called as such:
# obj = MyQueue()
# obj.push(1)
# obj.push(2)
# param_2 = obj.pop()
# param_3 = obj.peek()
# param_4 = obj.empty()

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章