Code /* GTestStack.java Dave Klick 2014-03-26 Stack implementation that accepts any type of object. */ class Stack { private class Node { T data; Node next; public Node(T obj) { data = obj; next = null; } public Node(Node n) { data = n.data; next = null; } } private Node head = null; private int count = 0; public void push(T obj) { Node newnode = new Node(obj); newnode.next = head; head = newnode; count++; } public boolean isEmpty() { return head == null; } public int length() { return count; } public int size() { return count; } public T peek() { if (head == null) return null; else return head.data; } public T pop() { if (head == null) return null; else { T data = head.data; head = head.next; count--; return data; } } public void clear() { while (!isEmpty()) pop(); } public String toString() { StringBuilder s = new StringBuilder(); Node cur = head; while (cur != null) { if (s.length() > 0) s.append(", "); s.append(cur.data.toString()); cur = cur.next; } return s.toString(); } } public class GTestStack { public static void main(String[] args) { Stack stk = new Stack(); stk.push(new String("Item 1")); stk.push(new String("Item 2")); stk.push(new String("Item 3")); stk.push(new String("Item 4")); System.out.println(stk); System.out.println(stk.length()); System.out.println(stk.peek()); while (!stk.isEmpty()) { System.out.println("Removed: " + stk.pop()); } System.out.println(stk.length()); } }