Custopootimus

Recursive Polymorphic Stack

Mar 31st, 2013
430
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.92 KB | None | 0 0
  1. /* A recursive, polymorphic implementation of a stack */
  2. public class Stack<T> {
  3.     /** Return true if the collection is empty */
  4.     public boolean isEmpty() { return true; }
  5.  
  6.     /** Return the top element on the stack */
  7.     public T peek() { return null; }
  8.        
  9.     /** Return the stack, sans top element */
  10.     public Stack<T> pop() { return this; }
  11.    
  12.     /** Return a new stack with a given item at the top */
  13.     public Stack<T> push(final T elem) {
  14.         return new Stack<T>() {
  15.             public T peek() { return elem; }
  16.             public Stack<T> pop() { return Stack.this; }
  17.             public boolean isEmpty() { return false; }
  18.         };}
  19. }
  20.  
  21. /* Sample usages */
  22.  
  23. /* Add entries to a stack */
  24. Stack<String> animals = new Stack<T>()
  25.     .push("Dog")
  26.     .push("Rat")
  27.     .push("Cat");
  28.  
  29. /* A generic print method for a stack */
  30. static <T> void print(Stack<T> stack) {
  31.     while (!stack.isEmpty()) {
  32.         System.out.println(stack.peek());
  33.         stack = stack.pop();
  34.     }
  35. }
Advertisement
Add Comment
Please, Sign In to add comment