import java.util.ArrayList; import java.util.List; /** * IntStack implements a basic stack data structure for integers. * * @author Krysta Yousoufian * */ public class IntStack { private List values; /** * @effects creates an empty IntStack */ public IntStack() { values = new ArrayList(); } /** * Checks whether the stack has elements in it. * @return true if there are no elements in the list, false otherwise */ public boolean isEmpty() { return values.size() == 0; } public int size() { return values.size(); } /** * Reveals top element without removing it. * * @requires isEmpty() is false * @throws IllegalStateException if isEmpty() is true * @return top element of stack */ public int peek() { if (values.isEmpty()) throw new IllegalStateException("No elements in list"); else return values.get(values.size()-1); } public int pop() { if (values.isEmpty()) throw new IllegalStateException("No elements in list"); else return values.remove(values.size()-1); } /** * Pushes an item onto the stack. * @modifies this * @effects adds n to the top of the stack * @param n the value to add */ public void push(int n) { values.add(n); } public static void combine(IntStack source, IntStack dest) { // Pushing values directly from source to dest would reverse the order. Use // tmp as an intermediate step to maintain order. IntStack tmp = new IntStack(); while (!source.isEmpty()) tmp.push(source.pop()); while (!tmp.isEmpty()) dest.push(tmp.pop()); } /** * Copies items in one list to another. * @modifies dest * @effects copies all elements in source to the top of dest in the same order, leaving a copy * in source. The top element in source becomes the top element in dest while the bottom element * in dest remains unchanged. * @param source the stack from which to copy elements * @param dest the stack to which to add elements */ public static void copy(IntStack source, IntStack dest) { IntStack tmp = new IntStack(); while (!source.isEmpty()) tmp.push(source.pop()); while (!tmp.isEmpty()) { int n = tmp.pop(); source.push(n); dest.push(n); } } }