import java.util.LinkedList; import java.util.ListIterator; /** Let's implement a stack using a LinkedList. */ public class LinkedListStack implements StackInterface { private LinkedList list; public LinkedListStack() { list = new LinkedList(); } public void push(Object o) { System.out.println("pushing " + o); list.add(o); } public Object pop() { Object victim = peek(); list.remove(list.size() - 1); System.out.println("popping " + victim); return victim; } public Object peek() { return list.get(list.size() - 1); } public int size() { return list.size(); } // We want to show the top (end) of the stack on top, so the iterator // starts at size. The parameter we pass to listIterator() starts the // iterator point to the element that would be returned if we call next. public String toString() { StringBuilder build = new StringBuilder(); ListIterator iter = list.listIterator(list.size()); while(iter.hasPrevious()) { build.append("\t" + iter.previous() + "\n"); } return build.toString(); } }