如有不足,请批评指正
1构建队
import java.util.Stack;
public class MyQueue {
static Stack<Character> stack1=new Stack<>();
static Stack<Character> stack2=new Stack<>();
public void enQueue(char ch){
stack1.push(ch);
}
public MyQueue(Character[] array){
for(int i=0;i<array.length;i++)
enQueue(array[i]);
}
public MyQueue() {
// TODO Auto-generated constructor stub
}
public void deQueue( ){
if(stack1.isEmpty()) return;
while(stack1.isEmpty()==false){
char ch=stack1.pop();
stack2.push(ch);
}
stack2.pop();
while(stack2.isEmpty()==false)
{ char ch=stack2.pop();
stack1.push(ch);
}
}
public void print(){
System.out.println("the items in the queue are:");
if(stack1.isEmpty()) return;
while(stack1.isEmpty()==false){
char ch=stack1.pop();
stack2.push(ch);
}
//stack2.pop();
while(stack2.isEmpty()==false)
{ char ch=stack2.pop();
System.out.print(ch+" ");
stack1.push(ch);
}
System.out.println();
}
}
2 测试结果:
public class TestMyQueue {
public static void main(String[] args){
Character[] array={'A','B','C','D'};
MyQueue queue=new MyQueue(array);
queue.print();
queue.deQueue();
queue.print();
queue.enQueue('E');
queue.print();
queue.deQueue();
queue.print();
queue.deQueue();
queue.print();
queue.deQueue();
queue.print();
queue.deQueue();
queue.print();
}
}
实验结果:
the items in the queue are:
A B C D
the items in the queue are:
B C D
the items in the queue are:
B C D E
the items in the queue are:
C D E
the items in the queue are:
D E
the items in the queue are:
E
the items in the queue are: