剑指offer——用两个栈实现队列

我会带着你远行 2022-05-17 10:21 317阅读 0赞

题目

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

实现及原理

  • 栈,具有先进后出的特点;而队列具有先进先出的特点
  • 通过两个栈实现队列的特点,那么一个栈就需要作为压入栈,一个栈作为弹出栈。压入数据进压入栈,弹出数据从弹出栈出。
  • 在弹出数据时,需要判断弹出栈中是否还有数据,若还有剩余数据未被弹出,则直接弹出数据。否则,需要从压入栈中将数据导入弹出栈,再进行数据的弹出。

参考代码

  1. import java.util.Stack;
  2. /**
  3. *
  4. * @author LXH
  5. *
  6. */
  7. public class StackToQueue {
  8. // 压入栈
  9. Stack<Integer> stack1 = new Stack<Integer>();
  10. // 弹出栈
  11. Stack<Integer> stack2 = new Stack<Integer>();
  12. public void push(int node) {
  13. stack1.push(node);
  14. }
  15. public int pop() {
  16. // 如果两个队列均为空,则不能在进行弹出操作,抛出运行时异常。
  17. if(stack1.empty() && stack2.empty()) {
  18. throw new RuntimeException("Queue is Empty");
  19. }
  20. // 若弹出栈不为空,则直接从弹出站中弹出相应的数据即可。
  21. if(!stack2.empty()) {
  22. return stack2.pop();
  23. }
  24. // 否则,需要将数据从压入栈中倒进弹出栈。
  25. while(!stack1.isEmpty()) {
  26. stack2.push(stack1.pop());
  27. }
  28. return stack2.pop();
  29. }
  30. public static void main(String[] args) {
  31. StackToQueue stackToQueue = new StackToQueue();
  32. stackToQueue.push(0);
  33. stackToQueue.push(1);
  34. stackToQueue.push(2);
  35. stackToQueue.push(3);
  36. stackToQueue.push(4);
  37. stackToQueue.push(5);
  38. stackToQueue.push(6);
  39. System.out.println(stackToQueue.pop());
  40. System.out.println(stackToQueue.pop());
  41. System.out.println(stackToQueue.pop());
  42. System.out.println(stackToQueue.pop());
  43. System.out.println(stackToQueue.pop());
  44. }
  45. }

运行结果

70

  1. 本题作为剑指offer中的题目,还是很受面试官们的青睐的,前一段时间的京东面试官就问到了这个题目的变形题目,不过万变不离其宗。把握住其中心思想,相信其他变形题目大家也是可以解决的。

发表评论

表情:
评论列表 (有 0 条评论,317人围观)

还没有评论,来说两句吧...

相关阅读