package username.linear; import username.util.DynamicArray; /** * Part of an array-based implementation of stacks. * * @author Samuel A. Rebelsky * @version 1.0 of April 2006 */ // +-------+------------------------------------------------------------- // | Notes | // +-------+ /* We use a dynamic array to store the values in the stack. The initial element to get added gets put in index 0, the next element goes in index 1, and so on and so forth. An integer, size, keeps track of the next location to which we'll add a value. */ public class ArrayBasedStack implements Stack { // +--------+------------------------------------------------------------ // | Fields | // +--------+ /** The array that stores the values. */ DynamicArray stuff; /** The place in which the next value goes. */ int size; // +-------------+------------------------------------------------------- // | Construtors | // +-------------+ /** * Build a new stack. */ public ArrayBasedStack() { // Use an array whose size starts relatively small. this.stuff = new DynamicArray(8); // The stack is empty, so the next element goes at 0. this.size = 0; } // ArrayBasedStack() // +---------+----------------------------------------------------------- // | Methods | // +---------+ /** * Add an element to the stack. * * @param val * The object that is to be added. * @post * The stack now contains an additional copy of val. */ public void put(T val) { this.stuff.set(this.size, val); ++this.size; } // put(T) /** * Remove the most-recently-added element that is still in the * stack. * * @return val * An object in the structure. * @pre * The structure is not empty. * @post * The structure contains one fewer copy of val. * @post * Every value in the stack was added less recently than val. */ public T get() { --this.size; // Remember the element we're about to return. T returnme = this.stuff.get(this.size); // For safety, we clean out that part of the array. this.stuff.set(this.size, null); return returnme; } // get() /** * Determine which object will next be returned by get. * * @return val * An object in the stack * @pre * The structure is not empty. * @post * Every other value in the stack was added less recently than val. */ public T peek() { return this.stuff.get(this.size-1); } // peek() /** * Determine if the stack is empty. */ public boolean isEmpty() { return (this.size == 0); } // isEmpty() } // class ArrayBasedStack