更改队列里数组大小。未解决,书上更改栈例题好像有问题。
package luyunzhou.one;
import java.util.Scanner;
/**
* 未解决
*
*
*/
public class Answer1314unfinished {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner scanner = new Scanner(System.in);
ResizingArrayQueueOfStrings<Integer> queue = new ResizingArrayQueueOfStrings<Integer>();
for (int i = 0; i < 5; i++) {
queue.enqueue(scanner.nextInt());
}
int i = 0;
while(i < 5){
System.out.println(queue.dequeue());
++i;
}
}
}
class ResizingArrayQueueOfStrings<Item>{
private Item[] a = (Item[]) new Object[1];
private int N = 0;
private int first = 0;
private int last = 0;
public boolean isEmpty() {
return N == 0;
}
public int size() {
return N;
}
public void resize(int max) {
Item[] item = (Item[]) new Object[max];
for (int i = 0; i < N; i++) {
item[i] = a[i];
}
N = max;
a = item;
}
public void enqueue(Item item) {
if(N+1 == a.length){
resize(2*a.length);
}
System.out.println(N);
if(N == 0){
a[N] = item;
}else {
a[N+1] = a[N];//数组越界????????
a[N] = item;
}
N++;
}
public Item dequeue() {
if(N > 0 && N+1 == a.length/4){
resize(a.length/2);
}
Item item = a[N];
a[N] = null;
N--;
return item;
}
}