题目描述 用两个栈来实现一个队列,完成队列的Push和Pop操作. 队列中的元素为int类型. 思路: 1.一个栈用来做push 2.另一个栈用来做pop 3.将push操作的栈的元素放入另一个栈中,实现先进先出 class Solution { public: void push(int node) { stack1.push(node); } int pop() { if(stack2.empty()) { while(!stack1.empty()) { int num = stack1.…
算法:用两个栈来实现一个队列,完成队列的Push和Pop操作. 队列中的元素为int类型.<剑指offer> 利用栈来进行操作,代码注释写的比较清楚:首先判断两个栈是否是空的:其次当栈二 为空,将栈1中取出来放到栈二,最终返回栈二首部值: 主要利用了pop()方法和push方法: package LG.nowcoder; /** * @Author liguo * @Description 用两个栈来实现一个队列,完成队列的Push和Pop操作. 队列中的元素为int类型. * @Data 2…
题目 用两个栈来实现一个队列,完成队列的Push和Pop操作. 队列中的元素为int类型. 思路: 一个栈压入元素,而另一个栈作为缓冲,将栈1的元素出栈后压入栈2中 代码 import java.util.Stack; /** *两个栈实现一个队列 * @author MSI */ public class Requeue{ Stack<Integer> sk1=new Stack<Integer>(); Stack<Integer> sk2=new Stack<…
1. 题目描述 用两个栈来实现一个队列,完成队列的Push和Pop操作. 队列中的元素为int类型. 2. 思想 (1)栈的特点是先进后出,而队列的特点是先进先出: (2)因此,入队列的情况和入栈的情况一样stack.push(),用一个栈来模拟就可以了: (3)而出栈为出栈顶的元素,也即和输入相反(先进后出):然而出队为先进先出,因此借助第2个栈,将第一个站的元素放入第2栈中,再将第2个栈中的元素出栈,也即翻转两次实现了先进先出: (4)第2个栈为出队列用,当栈2为空时,将栈1中的元素入栈2:…
// test14.cpp : 定义控制台应用程序的入口点. // #include "stdafx.h" #include<iostream> #include<string> #include<cctype> #include <vector> #include<exception> #include <initializer_list> #include<stack> using namespac…
一  基本思路 将s1作为存储空间,以s2作为临时缓冲区. 入队时,将元素压入s1. 出队时,将s1的元素逐个“倒入”(弹出并压入)s2,将s2的顶元素弹出作为出队元素,之后再将s2剩下的元素逐个“倒回”s1. 二 图示 三 代码实现(Java) import java.util.Stack; public class Solution { Stack<Integer> stack1 = new Stack<Integer>(); Stack<Integer> stac…
public class Solution { Stack<Integer> stack1 = new Stack<Integer>(); Stack<Integer> stack2 = new Stack<Integer>(); public void push(int node) { stack1.push(node); } public int pop() { if(stack1.empty()&&stack2.empty()){ th…
题目: 用两个栈来实现一个队列,完成队列的Push和Pop操作. 队列中的元素为int类型. 分析: 栈的特点是先进后出,队列的特点则是先进先出. 题目要求我们用两个栈来实现一个队列,栈和队列都有入栈(入队)的操作,所以我们可以使用一个栈来模拟入队的操作,另一个栈用来负责出队. 利用stack1模拟入队操作,stack2模拟出队操作. 当有元素入队时,就直接压入stack1中,当要出出队时,stack1中元素弹出的顺序和要求出队的顺序是正好相反的,我们可以将stack1的元素依次弹出,再压入st…
题目描述 用两个栈来实现一个队列,完成队列的Push和Pop操作. 队列中的元素为int类型.   思路: 入队:将元素进栈A 出队:判断栈B是否为空,如果为空,则将栈A中所有元素pop,并push进栈B,栈B出栈: 如果不为空,栈B直接出栈. class Solution { public: void push(int node) { stack1.push(node); } int pop() { int a; if(stack2.empty()) { while(!stack1.empty…
题目描述:用两个栈来实现一个队列,完成队列的Push和Pop操作. 队列中的元素为int类型. 首先定义两个栈 Stack<Integer> stack1 = new Stack<Integer>();//作为进队的端口 Stack<Integer> stack2 = new Stack<Integer>();//作为出对的端口 思路:两个栈,有两个端口,那么肯定一个是用来入队的,另一个用来出队的.同时,由于栈是先进后出的,那么经过两次的入栈则会变为先进先出…