CLRS10.1-7练习

算法中心思想:

始终向非空队列进行入队操作

初始化时两个队列都为空,我们对q1进行入队操作

入栈:

只需执行其中一个队列入队操作即可,

具体操作哪一个队列,用一个标记变量标记 

出栈流程图

代码实现

 1 package hello;
 2 import java.util.*;
 3 
 4 public class TwoQueueOneStack<E> {
 5     private Queue<E> q1 = new LinkedList<>();
 6     private Queue<E> q2 = new LinkedList<>();
 7     private String pushFlag = "q1";
 8 
 9     public void push(E item){
10         if(pushFlag == "q1"){
11             q1.add(item);
12         }
13         if(pushFlag == "q2"){
14             q2.add(item);
15         }
16     }
17 
18     public E pop(){
19         E top;
20         if(!empty()){
21             if(!q1.isEmpty()) {
22                 top = move(q1, q2);
23                 this.pushFlag = "q2";
24             } else {
25                 top = move(q2, q1);
26                 this.pushFlag = "q1";
27             }
28         }else{
29             throw new ArrayIndexOutOfBoundsException();
30         }
31         return top;
32     }
33 
34     private E move(Queue<E> qSource, Queue<E> qTarget){
35         Iterator<E> it = qSource.iterator();
36         while(it.hasNext()){
37             E item = it.next();
38             if(it.hasNext()){
39                 qTarget.add(item);
40             }else{
41                 qSource.clear();
42                 return item;
43             }
44         }
45 
46         throw new ArrayIndexOutOfBoundsException();
47     }
48 
49     public boolean empty(){
50         if (q1.isEmpty() && q2.isEmpty())
51             return true;
52         else
53             return false;
54     }
55 
56     public static void main(String[] args){
57         TwoQueueOneStack<Integer> tqos = new TwoQueueOneStack<>();
58         for (int i = 0; i < 20; i++) {
59             tqos.push(i);
60         }
61         for (int i = 0; i < 10; i++){
62             System.out.println(tqos.pop());
63         }
64         for (int i = 20; i < 40; i++){
65             tqos.push(i);
66         }
67         for (int i = 0; i < 30; i++){
68             System.out.println(tqos.pop());
69         }
70     }
71 
72 }
原文地址:https://www.cnblogs.com/dgzhangning/p/7651604.html