用两个队列实现一个栈,实现栈的push压栈,pop出栈,top查看栈顶元素以及是否为空等基本操作。

基本思想如上图所示:

在push的时候,往非空的那个队列添加(刚刚初始化的时候,两个队列都为空,随便往哪个队列push都行 上图步骤1和步骤3

在pop的时候,如果队列1不为空,就把队列1中q1.size()-1个元素poll出来,添加到队列2中(上图步骤2中元素1和2),再把队列中那个最后的元素poll出来(步骤2中元素3)

这两个队列中始终有一个是空的。另一个非空。push添加元素到非空队列中,pop把非空队列中前面的元素都转移到另一个队列中,只剩最后一个元素,再把最后一个元素pop出来。这样这一个队列是空的,另一个队列又非空了。

Java实现的代码:

  1. class Stack{
  2. LinkedList<Integer> queue1 = new LinkedList<Integer>(); //队列1
  3. LinkedList<Integer> queue2 = new LinkedList<Integer>(); //队列2
  4. // Push element x onto stack.
  5. public void push(int x) {
  6. if(!queue2.isEmpty()){
  7. queue2.offer(x);
  8. }else{
  9. queue1.offer(x);
  10. }
  11. }
  12. // Removes the element on top of the stack.
  13. public void pop() {
  14. if(!empty()){
  15. if(queue1.isEmpty()){
  16. while(queue2.size() > 1){
  17. queue1.offer(queue2.poll());
  18. }
  19. queue2.poll();
  20. }else{
  21. while(queue1.size() > 1){
  22. queue2.offer(queue1.poll());
  23. }
  24. queue1.poll();
  25. }
  26. }
  27. }
  28. // Get the top element.
  29. public int top() {
  30. if(queue1.isEmpty()){
  31. while(queue2.size() > 1){
  32. queue1.offer(queue2.poll());
  33. }
  34. int x = queue2.poll();
  35. queue1.offer(x);
  36. return x;
  37. }else{
  38. while(queue1.size() > 1){
  39. queue2.offer(queue1.poll());
  40. }
  41. int x = queue1.poll();
  42. queue2.offer(x);
  43. return x;
  44. }
  45. }
  46. // Return whether the stack is empty.
  47. public boolean empty() {
  48. return queue1.isEmpty() && queue2.isEmpty();
  49. }
  50. }