ResizingArrayStack 動態調整陣列大小
阿新 • • 發佈:2018-12-13
package com.arithmetic; import java.util.Iterator; import java.util.NoSuchElementException; // 能夠動態調整陣列大小的實現 public class ResizingArrayStack<Item> implements Iteratable<Item> { private Item[] a; // 棧元素 private int N; ResizingArrayStack(int cap) { a = (Item[]) new Object[cap]; N = 0; } // 新增時檢查陣列大小,如果棧的大小和陣列大小一致,那麼將原來陣列長度加倍 void push(Item item) { if (N == a.length) { resize(2 * a.length); } a[N++] = item; } // 刪除棧頂元素,如果陣列較大,可以將其長度減半 Item pop() { if (isEmpty()) throw new NoSuchElementException("Stack underflow"); Item item = a[N - 1]; a[N - 1] = null; // to avoid loitering N--; // shrink size of array if necessary if (N > 0 && N == a.length / 4) resize(a.length / 2); return item; } int size() { return N; } boolean isEmpty() { return N == 0; } // 實現一個方法,將棧移動到另外一個大小不同的陣列中 private void resize(int max) { Item[] temp = (Item[]) new Object[max]; for (int i = 0; i < N; i++) { temp[i] = a[i]; } a = temp; } @Override public Iterator<Item> iterator() { return new ReverseArrayIterator(); } private class ReverseArrayIterator implements Iterator<Item> { private int i; public ReverseArrayIterator() { i = N - 1; } @Override public boolean hasNext() { return i >= 0; } @Override public Item next() { if (!hasNext()) throw new NoSuchElementException(); return a[i--]; } @Override public void remove() { throw new UnsupportedOperationException(); } } public static void main(String[] args) { ResizingArrayStack stack = new ResizingArrayStack<>(100); stack.push(1); stack.push(2); stack.push(3); Iterator it = stack.iterator(); while (it.hasNext()) { System.out.println("Iterator : " + it.next()); } } }