Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /* A recursive, polymorphic implementation of a stack */
- public class Stack<T> {
- /** Return true if the collection is empty */
- public boolean isEmpty() { return true; }
- /** Return the top element on the stack */
- public T peek() { return null; }
- /** Return the stack, sans top element */
- public Stack<T> pop() { return this; }
- /** Return a new stack with a given item at the top */
- public Stack<T> push(final T elem) {
- return new Stack<T>() {
- public T peek() { return elem; }
- public Stack<T> pop() { return Stack.this; }
- public boolean isEmpty() { return false; }
- };}
- }
- /* Sample usages */
- /* Add entries to a stack */
- Stack<String> animals = new Stack<T>()
- .push("Dog")
- .push("Rat")
- .push("Cat");
- /* A generic print method for a stack */
- static <T> void print(Stack<T> stack) {
- while (!stack.isEmpty()) {
- System.out.println(stack.peek());
- stack = stack.pop();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment