Java棧的數組實現

// ALGORITHM 1.1 Pushdown (LIFO) stack (resizing array implementation)
import java.util.Iterator;

public class ResizingArrayStack<Item> implements Iterable<Item> {
	private Item[] a = (Item[]) new Object[1];
	private int N = 0;

	public boolean isEmpty() { return N == 0; }
	public int size() { return N; }

	private void resize(int max) {
		// Move stack to a new array of size max
		Item[] temp = (Item[])new Object[max];
		for (int i = 0; i < N; i++)
			temp[i] = a[i];
		a = temp;
	}

	public void push(Item item) {
		// Add item to top of stack
		if (N == a.length)
			resize(2 * a.length);

		a[N++] = item;
	}

	public Item pop() {
		// Remove item from top of stack
		Item item = a[--N];
		a[N] = null;	// Avoiding loitering

		if (N > 0 && N == a.length/4)
			resize(a.length/2);

		return item;
	}

	public Iterator<Item> iterator() {
		return new ReverseArrayIterator();
	}

	private class ReverseArrayIterator implements Iterator<Item> {
		// Support LIFO iteration
		private int i = N;

		public boolean hasNext() { return i > 0; }
		public Item next() { return a[--i]; }
		public void remove() {}
	}
}

優點java

1. Each operation should require time independent of the collection size算法

2. The space used should always be within a constant factor of the collection sizeui

缺陷:Some push and pop operations require resizing: this takes time proportional to the size of the stackthis

引自Robert Sedgewick算法第四版第141頁spa

相關文章
相關標籤/搜索