1、两个栈实现队列
import java.util.Stack;
public class Solution {
Stack<Integer> stack1 = new Stack<Integer>();
Stack<Integer> stack2 = new Stack<Integer>();
/**
* stack1:用户加入数据,之压到stack1中
* stack2:只给用户返回数据
*/
public void push(int node) {
stack1.push(node);
}
public int pop() {
if(stack1.empty() && stack2.empty()){
throw new RuntimeException("Queue is empty");
}
/**
* 如果stack2不为空,直接给用户返回数据
* 如果为空,把stack1中的数据全部出栈,并全部压入stack2中,stack2弹出数据给用户
*/
if(stack2.empty()){
while(!stack1.empty()){
stack2.push(stack1.pop());
}
}
return stack2.pop();
}
}
2、两个队列实现栈
解题思路:根据栈的先入后出和队列的先入先出的特点
1、在push的时候,把元素向非空的队列内添加
2、在pop的时候,把不为空的队列中的size()-1份元素poll出来,添加到另为一个为空的队列中,再把队列中最后的元素poll出来。两个队列在栈不为空的情况下始终是有一个为空,另一个不为空的。push添加元素到非空的队列中,pop把非空队列的元素转移到另一个空的队列中,直到剩下最后一个元素,这个元素就是要出栈的元素(最后添加到队列中的元素)。
public class Test {
public static void main(String[] args) {
push(1);
push(2);
push(3);
pop();
push(4);
pop();
pop();
pop();
}
static Queue<Object> queue1 = new LinkedList<>();
static Queue<Object> queue2 = new LinkedList<>();
/**
* 向队列中执行入栈操作,把元素添加到非空的队列中
* @param item
*/
public static void push(Object item){
if(!queue1.isEmpty()){
queue1.offer(item);
}else{
queue2.offer(item);
}
System.out.println("入栈元素:" + item);
}
/**
* 出栈
* @return
*/
public static void pop(){
if(!(queue1.isEmpty() && queue2.isEmpty())){
if(queue1.isEmpty()){
while (queue2.size() > 1){
queue1.offer(queue2.poll());
}
System.out.println("出栈元素:" + queue2.poll());
}else{
if(queue2.isEmpty()){
while (queue1.size() > 1){
queue2.offer(queue1.poll());
}
System.out.println("出栈元素:" + queue1.poll());
}
}
}else{
//两个队列都是空的,异常
throw new RuntimeException("栈为空,无法执行出栈操作");
}
}
}