剑指offer每日一刷-2017年11月14日

来源:互联网 发布:人工智能武器 编辑:程序博客网 时间:2024/06/10 12:54

 
 题目描述
 用两个栈来实现一个队列,完成队列的Push和Pop操作。 

 队列中的元素为int类型。

思路:

入队:将元素压入栈1

出队:栈2为空时,将栈1中的所有元素弹出,一一压入栈2,之后弹出栈2的元素;栈2不为空时,直接弹出栈2的元素即可。

public class StackQueue {Stack<Integer> stack1 = new Stack<Integer>();Stack<Integer> stack2 = new Stack<Integer>();public void push(int node){ stack1.push(node);}public int pop(){if(stack2.isEmpty()){while(!stack1.isEmpty()){stack2.push(stack1.pop());}return stack2.pop();}else{return stack2.pop();}}}