如果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; } }
*/functionpush($x){while(!$this->empty()) {$this->stack2[] =array_pop($this->stack1); }$this->stack1[] =$x;while(!empty($this->stack2)) {$this->stack1[] =array_pop($this->stack2); } }/** * Removes the element from in front of queue and returns that element. *@re...
LeetCode笔记:232. 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. em......
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. ...
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...
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. ...
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....
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//...
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. ...