- 1、题目描述:
-3、 设计思想:
详细操作流程看下图:
-4、视频讲解链接B站视频讲解
-5、代码:
c++版本:
class Solution
{
public:
void push(int node) {
stack1.push(node);//直接入栈1
}
int pop() {
/*如果栈2为空就代表没有进行过出队操作
所以需要把栈1里面的元素全部压入栈2中,进行模拟队的出队操作
*/
if(stack2.empty()){
while(!stack1.empty()){
stack2.push(stack1.top());
stack1.pop();
}
}
/*如果栈2不为空就代表之前的操作已经使用过出队操作,直接取出栈2的栈顶
元素就是当前出队的那个元素*/
int res = stack2.top();
stack2.pop();
return res;
}
private:
stack<int> stack1;//用来模拟队列的压入操作
stack<int> stack2;//用来模拟队列的弹出操作
};
Java版本:
import java.util.Stack;
public class Solution {
Stack<integer> stack1 = new Stack<integer>();//用来模拟队列的压入操作
Stack<integer> stack2 = new Stack<integer>();//用来模拟队列的弹出操作
public void push(int node) {
stack1.push(node);//直接入栈1
}
public int pop() {
/*如果栈2为空就代表没有进行过出队操作
所以需要把栈1里面的元素全部压入栈2中,进行模拟队的出队操作
*/
if(stack2.isEmpty()){
while(!stack1.isEmpty()){
stack2.push(stack1.pop());
}
}
/*如果栈2不为空就代表之前的操作已经使用过出队操作,直接取出栈2的栈顶
元素就是当前出队的那个元素*/
return stack2.pop();
}
}
Python版本:
# -*- coding:utf-8 -*-
class Solution:
def __init__(self):
self.stack1 = []#用来模拟队列的压入操作
self.stack2 = []#用来模拟队列的弹出操作
def push(self, node):
# write code here
self.stack1.append(node) #直接入栈1
def pop(self):
# return xx
'''
如果栈2为空就代表没有进行过出队操作
所以需要把栈1里面的元素全部压入栈2中,进行模拟队的出队操作
'''
if not self.stack2:
while self.stack1:
self.stack2.append(self.stack1.pop())
'''
如果栈2不为空就代表之前的操作已经使用过出队操作,直接取出栈2的栈顶
元素就是当前出队的那个元素
'''
return self.stack2.pop()
JavaScript版本:
let stack1 = []//用来模拟队列的压入操作
let stack2 = []//用来模拟队列的弹出操作
function push(node)
{
// write code here
stack1.push(node);//直接入栈1
}
function pop()
{
// write code here
/*如果栈2为空就代表没有进行过出队操作
所以需要把栈1里面的元素全部压入栈2中,进行模拟队的出队操作
*/
if(stack2.length == 0){
while(stack1.length > 0){
stack2.push(stack1.pop());
}
}
/*如果栈2不为空就代表之前的操作已经使用过出队操作,直接取出栈2的栈顶
元素就是当前出队的那个元素*/
let res = stack2.pop();
return res;
}
module.exports = {
push : push,
pop : pop
};
京公网安备 11010502036488号