Advertisement
Guest User

Untitled

a guest
Apr 11th, 2014
329
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.24 KB | None | 0 0
  1. class ListStack {
  2.  
  3.     int value;
  4.     int size;
  5.     ListStack next;
  6.  
  7.     public ListStack () {
  8.         this.size = 0;
  9.     }
  10.    
  11.     private ListStack (int add, ListStack head) {
  12.         this.value = add;
  13.         this.next = head;
  14.     }
  15.    
  16.     public void push (int add) {
  17.         this.next = new ListStack(this.value, this.next);
  18.         this.value = add;
  19.         this.size++;
  20.     }
  21.  
  22.     public int pop() {
  23.         if (this.size > 0) {
  24.             int i = this.value;
  25.             this.value = this.next.value;
  26.             this.next = this.next.next;
  27.             this.size--;
  28.             return i;
  29.         } else {
  30.             throw new EmptyListStackException();
  31.         }
  32.     }
  33.    
  34.     public int peek() {
  35.         return this.value;
  36.     }
  37.    
  38.     public void print() {
  39.         String aString = "";
  40.         ListStack p = this;
  41.         for (int i = 1; i < this.size; i++, p = p.next) {
  42.             aString += p.value+" -> ";
  43.         }
  44.         aString += "null";
  45.         System.out.println(aString);
  46.     }
  47.    
  48.     public class EmptyListStackException extends NullPointerException {
  49.         public EmptyListStackException() {
  50.             super("The list stack is empty, you cannot .pop() from it.");
  51.         }
  52.     }
  53. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement