如果stack 2 为空,则把 stack 1的元素全部移动到 stack 2,并返回栈顶元素 pop() 类似于peek,但是在返回的时候是移除操作并返回该元素。 1 读题 LeetCode 232E 用栈实现队列 Implement Queue using Stacks 2 Python 解题 正如咱们前面那个问题,list 既可以实现栈,还能实现列表,所以咱这题的代码,和那个队列模...
}returns2.pop(); }publicintpeek(){if(s2.isEmpty()) {while(!s1.isEmpty()) { s2.push(s1.pop()); } }returns2.peek(); }publicbooleanempty(){if(s1.isEmpty() && s2.isEmpty()) {returntrue; }else{returnfalse; } }
为了实现这种效果,在入队时,首先将栈1(假设栈1中保存所有的元素)中所有的元素弹出并压入栈2中,接着将新的元素压入栈1中,最后再将栈2中的所有弹出并压入栈1中。详细的步骤如图1所示。 图1:将一个元素入队 代码(Java)实现如下。 publicvoidpush(intx){// 将栈1中的所有元素弹出并压入栈2中while(!s1....
Implement the following operations of a queue using stacks. push(x) -- Push element x to the back of queue. pop() -- Removes the element from in front of queue. peek() -- Get the front element. empty() -- Return whether the queue is empty. Example: MyQueue queue = new MyQueue(...
public MyQueue() { } /** Push element x to the back of queue. */ public void push(int x) { while(!S.isEmpty()){ temp.push(S.pop()); } S.push(x); while(!temp.isEmpty()){ S.push(temp.pop()); } } /** Removes the element from in front of queue and returns that el...
【LeetCode题解】232_用栈实现队列(Implement-Queue-using-Stacks) 目录 描述 解法一:在一个栈中维持所有元素的出队顺序 思路 入队(push) 出队(pop) 查看队首(peek) 是否为空(empty) Java 实现 Python 实现 解法二:一个栈入,一个栈出 思路 入队(push) 出队(pop) 查看队首(peek) 是否为空(empty) Java...
Problem: Implement the following operations of a queue using stacks. push(x) -- Push element x to the back of queue. pop() -- Removes the element from in front of queue. peek() -- Get the front elemen...[leetcode] 232. Implement Queue using Stacks Question : Implement the followin...
LeetCode232:Implement Queue using Stacks Implement the following operations of a queue using stacks. push(x) – Push element x to the back of queue. pop() – Removes the element from in front of queue. peek() – Get the front element....
Implement the following operations of a queue using stacks. push(x) -- Push element x to the back of queue. pop() -- Removes the element from in front of queue. peek() -- Get the front element. empty() -- Return whether the queue is empty. ...
A classic interview question.This linkhas a nice explanation of the idea using two stacks and its amortized time complexity. I use the same idea in my code, which is as follows. 1classQueue {2public:3//Push element x to the back of queue.4voidpush(intx) {5stack1.push(x);6}78//...