两个栈实现队列和两个队列实现栈
一:两个队列实现栈
import java.util.Stack; 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.isEmpty()){ stack2.push(stack1.pop()); } int first = stack2.pop(); while(!stack2.isEmpty()){ stack1.push(stack2.pop()); } return first; } }
二:两个栈实现队列:
import java.util.Queue; import java.util.ArrayDeque; public class solution{ // 创建两个队列 Queue<Integer> queue1 = new ArrayDeque<Integer>(); Queue<Integer> queue2 = new ArrayDeque<Integer>(); // 入队 public void push(int node) { queue1.add(node); } // 出队 public int pop() { if (queue1.size() <= 1) { return queue1.poll(); } else { while (queue1.size() > 1) { queue2.add(queue1.poll()); } } while (queue2.size() > 0) { queue1.add(queue2.poll()); } return queue1.poll(); } }
Poll和pop的区别
poll:Queue(队列)的一个方法,获取并移除此队列的头,如果此队列为空,则返回null
pop:Stack(栈)的方法,移除堆栈顶部的对象,并作为此函数的值返回该对象

浙公网安备 33010602011771号