首页 > 其他 > 详细

Leetcode刷题日记-程序员面试经典(2020.6.23):化栈为队

时间:2020-06-24 09:52:51      阅读:58      评论:0      收藏:0      [点我收藏+]

题目描述:

技术分享图片

 

 思路整理:

此题为简单题,没啥说的,我们直接用两个栈,一个输入栈,一个输出栈即可来实现

代码:

#!/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()

 

Leetcode刷题日记-程序员面试经典(2020.6.23):化栈为队

原文:https://www.cnblogs.com/ZFJ1094038955/p/13185944.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!