Advertisement
Aldin-SXR

Stack.java

Mar 5th, 2020
193
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.92 KB | None | 0 0
  1. package ds.stack.regular;
  2.  
  3. public class Stack<Item> {
  4.     private Node<Item> top = null;
  5.     private int length = 0;
  6.  
  7.    
  8.     /* Push an item onto the stack */
  9.     public void push(Item item) {
  10.         Node<Item> newNode = new Node<Item>();  // 1
  11.         newNode.data = item;                    // 1
  12.         newNode.next = top;                     // 2
  13.         top = newNode;                          // 3
  14.         length++;                               // 4
  15.     }
  16.    
  17.     /* Check if the stack is empty */
  18.     public boolean isEmpty() {
  19.         return top == null;
  20.     }
  21.    
  22.     /* Remove the top item from the stack, and return its data */
  23.     public Item pop() {                                                    
  24.         if (isEmpty()) {                                                    // 1
  25.             throw new IndexOutOfBoundsException("The stack is empty.");     // 1
  26.         }                                                                   // 1
  27.         Item item = top.data;                                               // 2
  28.         top = top.next;                                                     // 3
  29.         length--;                                                           // 4
  30.         return item;                                                        // 5
  31.     }
  32.    
  33.     /* Return the current size of the stack */
  34.     public int size() {
  35.         return length;
  36.     }
  37. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement