Java 两个栈实现队列和两个队列实现栈

以你之姓@ 2022-07-18 01:24 370阅读 0赞

两个队列实现栈:

  1. package test;
  2. import java.util.Stack;
  3. public class TwoStackQueue {
  4. public Stack<Integer> stackPush;
  5. public Stack<Integer> stackPop;
  6. public TwoStackQueue(){
  7. stackPush = new Stack<Integer>();
  8. stackPop = new Stack<Integer>();
  9. }
  10. public void push(int num){
  11. while(!stackPop.isEmpty()){
  12. stackPush.push(stackPop.pop());
  13. }
  14. stackPush.push(num);
  15. }
  16. public int pop(){
  17. while(!stackPush.isEmpty()){
  18. stackPop.add(stackPush.pop());
  19. }
  20. return stackPop.pop();
  21. }
  22. public static void main(String args[]){
  23. TwoStackQueue test = new TwoStackQueue();
  24. test.push(1);
  25. test.push(2);
  26. test.push(3);
  27. System.out.println(test.pop());
  28. }
  29. }

两个队列实现栈

  1. package test;
  2. import java.util.LinkedList;
  3. import java.util.Queue;
  4. public class TwoQueueStack {
  5. public static Queue<Integer> queue1;
  6. public static Queue<Integer> queue2;
  7. public TwoQueueStack(){
  8. queue1 = new LinkedList<Integer>();
  9. queue2 = new LinkedList<Integer>();
  10. }
  11. public void push(int x) {
  12. if(empty()){
  13. queue1.offer(x);
  14. }else{
  15. if(!queue1.isEmpty()){
  16. queue2.offer(x);
  17. while(!queue1.isEmpty()){
  18. queue2.offer(queue1.poll());
  19. }
  20. }else if(!queue2.isEmpty()){
  21. queue1.offer(x);
  22. while(!queue2.isEmpty()){
  23. queue1.offer(queue2.poll());
  24. }
  25. }
  26. }
  27. }
  28. public static int pop(){
  29. if(!queue1.isEmpty()){
  30. return queue1.poll();
  31. }else if(!queue2.isEmpty()){
  32. return queue2.poll();
  33. }else{
  34. return 0;
  35. }
  36. }
  37. public boolean empty() {
  38. return queue1.isEmpty() & queue2.isEmpty();
  39. }
  40. public static void main(String args[]){
  41. TwoQueueStack test = new TwoQueueStack();
  42. test.push(1);
  43. test.push(2);
  44. System.out.println(pop());
  45. }
  46. }

发表评论

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

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

相关阅读