更多2019年的技术文章,欢迎关注我的微信公众号:码不停蹄的小鼠松(微信号:busy_squirrel),也可扫下方二维码关注获取最新文章哦~
T:
题目描述
用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
栈的特性是先进后出,队列的是先进先出,知道这点,基本上都能想到怎么做了。。。
还是说一下步骤:
- 队列的push()操作,就直接在stack1上进行栈的push()操作即可;
- 队列的pop()操作,其实就是得到stack1中最底下的那个元素,怎么得到呢?先把上面逐个退出的元素一个个放在另一个栈stack2中;
- 当stack1为空的时候,stack2的栈顶元素,就是要取得的元素,用栈的pop()操作取出,在将该元素进行返回前,再将stack2中的元素,倒回到stack1中,然后将该元素返回,over.
code:
package niuke.sward2offer.queueBy2Stack;
import java.util.Queue;
import java.util.Stack;
/**
* T: 用两个栈实现队列
*
* 题目描述
* 用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
*
* date: 2015.11.6 19:27
* @author SSS
*
*/
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() {
while (!stack1.empty()) {
Integer tempNode = stack1.pop();
stack2.push(tempNode);
}
int result = stack2.pop();
while (!stack2.empty()) {
stack1.push(stack2.pop());
}
return result;
}
public static void main(String []args) {
Solution solution = new Solution();
// solution.push(2);
// solution.push(3);
System.out.println(solution.pop());
solution.push(5);
// System.out.println(solution.pop());
// System.out.println(solution.pop());
}
}
更多2019年的技术文章,欢迎关注我的微信公众号:码不停蹄的小鼠松(微信号:busy_squirrel),也可扫下方二维码关注获取最新文章哦~