/** An instance of this class represents a stack capable of holding items ** of the specified type T (the generic type parameter). ** The underlying implementation makes use of a linked structure of ** objects arising from the Link1 class. ** ** Author: R. McCloskey ** Date: January 2020 */ public class StackViaLink1 implements Stack { // instance variables // ------------------ protected Link1 top; // reference to object holding top item on stack private int numItems; // # of items on the stack // constructors // ------------ /* Establishes this stack as being empty. */ public StackViaLink1() { clear(); } // observers // --------- public int sizeOf() { return numItems; } public boolean isEmpty() { return sizeOf() == 0; } public boolean isFull() { return false; } public T topOf() { return top.item; } public String toString() { Link1 pntr = top; StringBuilder s = new StringBuilder(); while (pntr != null) { s.append(pntr.item + ","); pntr = pntr.next; } return s.substring(0,Math.max(0, s.length()-1)); } // mutators // -------- public void clear() { top = null; numItems = 0; } public void push( T item ) { top = new Link1( item, top ); numItems = numItems + 1; } public T pop() { T result = top.item; top = top.next; numItems = numItems - 1; return result; } }