/** 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: September 2018 */ public class StackViaLink1 { /* i n s t a n c e v a r i a b l e s */ private Link1 top; // reference to Link1 object holding top item on stack private int numItems; // # of items on the stack /* c o n s t r u c t o r s */ /* Initializes the stack to be empty. */ public StackViaLink1() { top = null; numItems = 0; } /* o b s e r v e r s */ /* Returns the number of items on the stack. */ public int sizeOf() { return numItems; } /* Reports whether or not the stack has no items on it. */ public boolean isEmpty() { return sizeOf() == 0; } /* Returns (a reference to) the top item on the stack. ** pre: !isEmpty() */ public T topOf() { return top.getItem(); } public String toString() { String result = ""; if (!isEmpty()) { StringBuilder s = new StringBuilder(); Link1 node = top; while (node != null) { s.append(", " + node.getItem()); node = node.getNext(); } result = s.toString(); } return result; } /* m u t a t o r s */ /* Places the specified item onto the top of the stack. */ public void push( T item ) { top = new Link1( item, top ); numItems = numItems + 1; } /* Removes the top item from the stack. ** pre: !isEmpty() */ public void pop() { top = top.getNext(); numItems = numItems - 1; } }