算法(第四版)-1.3.14 编写一个类ResizingArrayQueueOfStrings,使用定长数组实现队列的抽象,然后扩展实现,使用调整数组的方法突破大小的限制。
问题
编写一个类ResizingArrayQueueOfStrings,使用定长数组实现队列的抽象,然后扩展实现,使用调整数组的方法突破大小的限制。
答案
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112
| package _1_3;
import java.util.Iterator; import java.util.NoSuchElementException;
public class _1_3_14 { public static void main(String[] args) { _1_3_14.Resizingarrayqueueofstrings<Integer> haha = new _1_3_14().new Resizingarrayqueueofstrings<Integer>(); for (int i = 1; i <= 10; i++) { haha.enqueue(i); } for (int i : haha) { System.out.println(i);
}
}
class Resizingarrayqueueofstrings<Item> implements Iterable<Item> { private int head; private int tail, N; private Item a[];
public Resizingarrayqueueofstrings() { a = (Item[]) new Object[2]; head = 0; tail = 0; N = 0; }
public int size() { return N; }
public boolean isEmpty() { return N == 0; }
public void enqueue(Item temp) { if (tail == a.length - 1) { resize(2 * a.length); } a[tail++] = temp; N++; }
private void resize(int num) { Item[] temp = (Item[]) new Object[num]; int haha = 0; for (int i = head; i <= tail - 1; i++) { temp[haha++] = a[i]; a[i] = null; } head = 0; tail = N; a = temp; }
public Item dequeue() { if (N == 0) throw new NoSuchElementException(); Item temp = a[head]; a[head] = null; head++; if (head > a.length / 2 + 1) { resize(a.length / 2); } N--; return temp; }
public Item peek() { int temp = head; while (temp < tail) return a[temp++]; return null; }
@Override public Iterator<Item> iterator() {
return new ReverseArrayIterator(); }
private class ReverseArrayIterator implements Iterator<Item> { private int i = 0; private int start = head;
@Override public boolean hasNext() {
return i < N; }
@Override public Item next() { i++; return a[start++];
}
}
} }
|