重要1.栈实现队列

image.png
push栈导数据到pop栈中有两个条件:①pop栈为空②push栈一次全部导入。

  1. public static class TwoStacksQueue {
  2. public Stack<Integer> stackPush;
  3. public Stack<Integer> stackPop;
  4. public TwoStacksQueue() {
  5. stackPush = new Stack<Integer>();
  6. stackPop = new Stack<Integer>();
  7. }
  8. // push栈向pop栈倒入数据
  9. private void pushToPop() {
  10. if(!stackPop.empty()){
  11. stackPop.clear();//清空stackPop
  12. }
  13. if (stackPop.empty()) {
  14. while (!stackPush.empty()) {
  15. stackPop.push(stackPush.pop());
  16. }
  17. }
  18. }
  19. public void add(int pushInt) {
  20. stackPush.push(pushInt);
  21. pushToPop();
  22. }
  23. public int poll() {
  24. if (stackPop.empty() && stackPush.empty()) {
  25. throw new RuntimeException("Queue is empty!");
  26. }
  27. pushToPop();
  28. return stackPop.pop();
  29. }
  30. public int peek() {
  31. if (stackPop.empty() && stackPush.empty()) {
  32. throw new RuntimeException("Queue is empty!");
  33. }
  34. pushToPop();
  35. return stackPop.peek();
  36. }
  37. }

2.队列实现栈

image.png
先将data队列中出队四个数到help队列中,然后把data的最后一个数出队列;其次让help和data互换,继续上面的操作。
栈中加入数字时就在data中入队列即可。

  1. public static class TwoQueueStack<T> {
  2. public Queue<T> queue;
  3. public Queue<T> help;
  4. public TwoQueueStack() {
  5. queue = new LinkedList<>();
  6. help = new LinkedList<>();
  7. }
  8. public void push(T value) {
  9. queue.offer(value);
  10. }
  11. public T poll() {
  12. while (queue.size() > 1) {
  13. help.offer(queue.poll());
  14. }
  15. T ans = queue.poll();
  16. Queue<T> tmp = queue;
  17. queue = help;
  18. help = tmp;
  19. return ans;
  20. }
  21. public T peek() {
  22. while (queue.size() > 1) {
  23. help.offer(queue.poll());
  24. }
  25. T ans = queue.poll();
  26. help.offer(ans);
  27. Queue<T> tmp = queue;
  28. queue = help;
  29. help = tmp;
  30. return ans;
  31. }
  32. public boolean isEmpty() {
  33. return queue.isEmpty();
  34. }
  35. }