// a Stack class // // This implements StackInterface // which guarantees the methods // isEmpty() // peek() // pop() and // push() class Stack implements StackInterface { /* StackCell is an inner class that Stack will * use to wrap its data in a linked list */ class StackCell { private Object data; private StackCell next; private StackCell(Object data) { this.data = data; this.next = next; } } /* the one data member of each Stack object */ private StackCell front; // the front of the stack (for pushing/popping) /* constructor * creates and empty stack */ public Stack() { front = null; } /* method: isEmpty * inputs: none * outputs: a boolean - whether or not this is empty */ public boolean isEmpty() { return (front == null); } /* method: push * inputs: an object to store at the front of the stack * outputs: none */ public void push(Object data) { StackCell newFront = new StackCell(data); if (isEmpty()) { this.front = newFront; } else { newFront.next = this.front; this.front = newFront; } } /* method: pop * inputs: none * outputs: the data that was at the front (null if empty) * pop also removes the front StackCell */ public Object pop() { if (isEmpty()) { System.out.println("You can't pop from an empty Stack!"); return null; } Object data = front.data; front = front.next; return data; } /* method: peek * inputs: none * outputs: the data that was at the front (null if empty) * peek does not alter the calling stack */ public Object peek() { if (isEmpty()) { System.out.println("You can't peek at an empty Stack!"); return null; } Object data = front.data; return data; } /* method: toString * inputs: none * outputs: the usual */ public String toString() { String result = " "; StackCell current = this.front; while (current != null) { result += "" + current.data + " "; current = current.next; } result += ""; return result; } /* method: main * inputs: the usual * outputs: none - a place for testing... */ public static void main(String[] args) { Stack S = new Stack(); System.out.println("S is " + S); S.push("Will"); System.out.println("S is " + S); S.push("this"); System.out.println("S is " + S); S.push("work?"); System.out.println("S is " + S); S.pop(); System.out.println("S is " + S); S.pop(); System.out.println("S is " + S); S.pop(); System.out.println("S is " + S); S.pop(); System.out.println("S is " + S); S.push("Will"); System.out.println("S is " + S); S.push("this"); System.out.println("S is " + S); S.push("work?"); System.out.println("S is " + S); } }