LeetCode 232. 用栈实现队列

原题链接:

https://leetcode.com/problems/implement-queue-using-stacks/description/

https://leetcode-cn.com/problems/implement-queue-using-stacks/description/

这道题其实比较简单,题目要求就是用栈实现一个队列。

我们考虑有两个栈,一个输入栈,一个输出栈。

放数据永远放入输入栈,取数据永远从输出栈取。

输出栈为空的时候把把输入栈的数据一次性取出来放到输出栈。

下面是 Java 和 Python 的代码

Java

class MyQueue {

    private Stack<Integer> input = null;
    private Stack<Integer> output = null;
    
    /** Initialize your data structure here. */
    public MyQueue() {
        
        input = new Stack<>();
        output = new Stack<>();
        
    }
    
    /** Push element x to the back of queue. */
    public void push(int x) {
        input.push(x);
    }
    
    /** Removes the element from in front of queue and returns that element. */
    public int pop() {
        if(output.isEmpty()) {
            while(!input.isEmpty()) {
                output.push(input.pop());
            }
        }
        return output.pop();
    }
    
    /** Get the front element. */
    public int peek() {
        if(output.isEmpty()) {
            while(!input.isEmpty()) {
                output.push(input.pop());
            }
        }
        return output.peek();
    }
    
    /** Returns whether the queue is empty. */
    public boolean empty() {
        return input.isEmpty() && output.isEmpty();
    }
}

Python

class MyQueue:

	def __init__(self):
		""" Initialize your data structure here. """
		self.instack = []
		self.outstack = []
		

	def push(self, x):
		""" Push element x to the back of queue. :type x: int :rtype: void """
		self.instack.append(x)
		

	def pop(self):
		""" Removes the element from in front of queue and returns that element. :rtype: int """
		if not self.outstack:
			while self.instack:
				self.outstack.append(self.instack.pop())
		return self.outstack.pop()
		

	def peek(self):
		""" Get the front element. :rtype: int """
		if not self.outstack:
			while self.instack:
				self.outstack.append(self.instack.pop())
		return self.outstack[-1]
		

	def empty(self):
		""" Returns whether the queue is empty. :rtype: bool """
		return not self.outstack and not self.instack

全部评论

相关推荐

07-02 10:44
门头沟学院 C++
码农索隆:太实诚了,告诉hr,你能实习至少6个月
点赞 评论 收藏
分享
想按时下班的我在等o...:我投测试也是这个情况,不知道咋办了
点赞 评论 收藏
分享
屌丝逆袭咸鱼计划:心态摆好,man,晚点找早点找到最后都是为了提升自己好进正职,努力提升自己才是最关键的😤难道说现在找不到找的太晚了就炸了可以鸡鸡了吗😤早实习晚实习不都是为了以后多积累,大四学长有的秋招进的也不妨碍有的春招进,人生就这样
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务