剑指offer第2版09题:用两个栈实现队列
小渣渣的算法学习笔记:2018秋招备战
数据结构类算法总结:栈和队列
数据结构类算法总结:栈和队列
1.题目描述:
用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
2.思路解析:根据具体例子分析队列插入和删除元素的过程
3.代码实现:
public class Solution05 { Stack<Integer> s1 = new Stack<>(); Stack<Integer> s2 = new Stack<>(); public static void main(String[] args) { Solution05 s = new Solution05(); for(int i=0;i<10;i++){ s.push(i); } for(int j = 0;j<10;j++){ System.out.print(s.pop()+ " "); } } public void push(int val){ s1.push(val); } public int pop(){ if(s2.isEmpty()){ while(!s1.isEmpty()){ s2.push(s1.pop()); } } return s2.pop(); } }