Guest User

Untitled

a guest
Jan 20th, 2018
282
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.85 KB | None | 0 0
  1. public interface Stack<T>
  2. {
  3.     T top();
  4.     Stack<T> pop();
  5.     Stack<T> push(T newTop);
  6.  
  7.     default Stack<T> push(T newTop)
  8.     {
  9.          return new NonEmpty<>(newTop, this);
  10.     }
  11.  
  12.     public class Empty<T> implements Stack<T>
  13.     {
  14.         public T top()
  15.         {
  16.             throw new EmptyStackException();
  17.         }
  18.    
  19.         public Stack<T> pop()
  20.         {
  21.             throw new EmptyStackException();
  22.         }
  23.     }
  24.  
  25.     public class NonEmpty<T> implements Stack<T>
  26.     {
  27.         private T top;
  28.         private Stack<T> tail;
  29.  
  30.         public NonEmpty(T newTop, Stack<T> previous)
  31.         {
  32.              top = newTop;
  33.              tail = previous;
  34.         }
  35.  
  36.         public T top()
  37.         {
  38.             return top;
  39.         }
  40.    
  41.         public Stack<T> pop()
  42.         {
  43.             return tail;
  44.         }
  45.     }
  46. }
Advertisement
Add Comment
Please, Sign In to add comment