4.2 根据本章里对双端队列的讨论编写一个Deque类,它应该包括insertLeft()、insertRight()、removeLeft()、removeRight()、 isEmpty()、isFull()方法。要求像队列那样支持在数据末端的回绕。
public class DuQueue {
private int maxSize;
private long[] queArray;
private int front;
private int rear;
private int nItems;
public DuQueue(int s){
maxSize=s;
queArray = new long[maxSize];
front=0;
rear=-1;
nItems=0;
}
public void insertLeft(long value){
if(front==0){
front=maxSize;
}
queArray[--front]=value;
nItems++;
}
public void insertRight(long value){
if(rear==maxSize-1){
rear=-1;
}
queArray[++rear]=value;
nItems++;
}
public long removeLeft(){
long temp = queArray[front++];
if(front==maxSize){
front=0;
}
nItems--;
return temp;
}
public long removeRight(){
long temp = queArray[rear--];
if(rear==-1){
rear=maxSize-1;
}
nItems--;
return temp;
}
public long peekLeft(){
return queArray[front];
}
public long peekRight(){
return queArray[rear];
}
public boolean isEmpty(){
return (nItems==0);
}
public boolean isFull(){
return (nItems==maxSize);
}
public int size(){
return nItems;
}
public void display(){
System.out.print("队列为: ");
if(nItems==0){
System.out.println("空。 ");
return;
}
if(rear>=front){
for(int i =front;i<=rear;i++){
System.out.print(queArray[i]+" ");
}
}
else{
for(int i =front;i<maxSize;i++){
System.out.print(queArray[i]+" ");
}
for(int i =0;i<=rear;i++){
System.out.print(queArray[i]+" ");
}
}
System.out.println();
}
}
public class DuQueueApp {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
DuQueue theQueue = new DuQueue(5);
theQueue.insertRight(10);
theQueue.insertRight(20);
theQueue.insertRight(30);
theQueue.insertRight(40);
theQueue.display();
System.out.println("移除"+theQueue.removeLeft());
System.out.println("移除"+theQueue.removeLeft());
System.out.println("移除"+theQueue.removeLeft());
theQueue.display();
theQueue.insertLeft(50);
theQueue.insertLeft(60);
theQueue.insertLeft(70);
theQueue.insertLeft(80);
theQueue.display();
theQueue.removeRight();
theQueue.removeRight();
theQueue.removeRight();
theQueue.display();
}
}