Advertisement
Aldin_SXR

Stack.java

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