Advertisement
zoltanvi

Stack Implementation in JAVA

Oct 21st, 2017
46
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.94 KB | None | 0 0
  1. import java.util.ArrayList;
  2.  
  3. /**
  4.  *  Write a Java program to implement Stack in Java
  5.  */
  6. public class StackImplementation {
  7.    private ArrayList<Object> container = new ArrayList<>();
  8.    private static int counter = -1;
  9.  
  10.     /**
  11.      * Pushes items into the stack
  12.      * @param object is the pushable object
  13.      */
  14.    public void push(Object object){
  15.        container.add(object);
  16.        counter++;
  17.    }
  18.  
  19.     /**
  20.      * Pops the last item from the stack
  21.      * @return the last item from the stack
  22.      */
  23.     public Object pop(){
  24.        if (!container.isEmpty()) {
  25.            Object temp = container.get(counter);
  26.            container.remove(counter);
  27.            counter--;
  28.            return temp;
  29.        }
  30.         return null;
  31.     }
  32.  
  33.     /**
  34.      * Checks if the stack is empty or not
  35.      * @return true if the stack is empty, false if not
  36.      */
  37.     public boolean isEmpty(){
  38.         return counter == -1;
  39.     }
  40.  
  41. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement