Down (LIFO) stack: an implementation that dynamically adjusts the size of the array
Import Java.util.iterator;public class resizingarraystack<item> implements iterable<item>{private int N = 0 ;p rivate item[] A = (item[]) new Object[1];p ublic boolean isEmpty () {return N = = 0;} public int size () {return N;} public void resize (int max) {item[] temp = (item[]) new object[max];for (int i = 0; i < N; i++) {temp[i] = a[i];} A = temp;} Public Item Pop () {Item item = A[--n];a[n] = null;if (n > 0 && n = = a.length/4) {resize (A.LENGTH/2);} return item;} public void push (item item) {if (N = = a.length) {Resize (a.length * 2);} a[n++] = Item;} @Overridepublic iterator<item> Iterator () {//TODO auto-generated method Stubreturn new Reversearrayiterator ();} Private class Reversearrayiterator implements iterator<item>{private int i = N; @Overridepublic boolean hasnext () {/ /TODO auto-generated method Stubreturn i > 0;} @Overridepublic Item Next () {//TODO auto-generated method Stubreturn a[--i];} @Overridepublic void Remove () {//TODO auto-generated Method stub}}}
Advantages:
Almost (but not useless) achieves the best performance for the implementation of any collection class data type:
1. The time of each operation is independent of the collection size;
2. Space requirements always do not exceed the set size multiplied by a constant.
Disadvantages:
Some push () and pop () operations adjust the size of the array, which is proportional to the amount of time spent on the stack.
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Algorithm (fourth edition) the Java implementation of the learning note can dynamically adjust the stack size of the array