05.用两个栈实现队列 Java

题目描述

用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。

思路

进栈:
	直接进stack1
出栈:
	若stack2不为空,则出栈。
	否则,当stack1不为空时,将stack1中的元素依次出栈并压人stack2中。最后,弹出stack2的栈顶元素。


package com.sysword.algo;

import java.util.Stack;

public class StackQueue {

private Stack<Integer> stack1 = new Stack<>();
private Stack<Integer> stack2 = new Stack<>();

public void push(Integer val) {
stack1.push(val);
}

public int pop(Integer val) {
if (stack2.isEmpty()) {
while (!stack1.isEmpty()) {
stack2.push(stack1.pop());
}
}

return stack2.pop();
}

}
 
原文地址:https://www.cnblogs.com/feicheninfo/p/10516681.html