1 class MyStack 2 { 3 private Queue q1; 4 private Queue q2; 5 6 public MyStack(int size) 7 { 8 this.q1 = new Queue(size); 9 this.q2 = new Queue(size); 10 } 11 12 public boolean isFull() 13 { 14 return q1.isFull(); 15 } 16 17 public boolean isEmpty() 18 { 19 return q1.isEmpty(); 20 } 21 22 //时间复杂度: O(n) 23 public void push(int k) throws Exception 24 { 25 if(this.isFull()) 26 throw new Exception("Overflow."); 27 else 28 { 29 while(!this.q1.isEmpty()) 30 this.q2.EnQueue(this.q1.DeQueue()); 31 this.q1.EnQueue(k); 32 while(!this.q2.isEmpty()) 33 this.q1.EnQueue(this.q2.DeQueue()); 34 } 35 } 36 37 //时间复杂度: O(1) 38 public int pop() throws Exception 39 { 40 if(this.isEmpty()) 41 throw new Exception("Underflow"); 42 else 43 return this.q1.DeQueue(); 44 } 45 } 46 47 class Queue 48 { 49 private int front; 50 private int rear; 51 private int[] a; 52 53 public Queue(int size) 54 { 55 this.front = this.rear = 0; 56 this.a = new int[size]; 57 } 58 59 public boolean isFull() 60 { 61 return (this.rear + 1) % this.a.length == this.front; 62 } 63 64 public boolean isEmpty() 65 { 66 return this.rear == this.front; 67 } 68 69 public void EnQueue(int k) throws Exception 70 { 71 //该判断是冗余的 72 /*if(this.isFull()) 73 * 74 throw new Exception("Overflow.");*/ 75 //else 76 { 77 this.a[this.rear] = k; 78 this.rear = (this.rear + 1) % this.a.length; 79 } 80 81 } 82 83 public int DeQueue() throws Exception 84 { 85 //该判断是冗余的 86 /*if(this.isEmpty()) 87 throw new Exception("Underflow.");*/ 88 //else 89 { 90 int key = this.a[front]; 91 this.front = (this.front + 1) % this.a.length; 92 return key; 93 } 94 } 95 96 public int getLength() 97 { 98 return (this.rear - this.front + this.a.length) % this.a.length; 99 } 100 }