Java implementation w/o Java Collections API [ACCEPTED]


  • 0
    I

    Here is my Java solution:

    Basic StackInterface:

    interface BasicStack {
      void push(int x);
      void pop();
      int top();
      boolean isEmpty();
    }
    

    Basic Implementaion:

    class StackImpl implements BasicStack {
      int stackSize = 0;
      int capacity = 10;
      int scaleFactor;
      int[] stack = new int[capacity];
      
      String name;
      boolean log = false;
      
      public StackImpl(String name, boolean log, int scaleFactor) {
        this.name = name;
        this.log = log;
        this.scaleFactor = scaleFactor;
      }
      public StackImpl(String name, boolean log) {
        this(name, log, 2);
      }
      
      public void push(int x) {
        if (shouldEncrease(stackSize + 1)) {
          encreaseCapasity();
        }
        log("capas", capacity);
        log("length", stack.length);
        log("push", x);
        stack[stackSize] = x;
        stackSize++;
      }
    
      public void pop() {
        if (stackSize != 0) {
            stack[stackSize] = 0;
            stackSize--;
        }
      }
    
      public int top() {
        if (stackSize == 0) {
          return 0;
        } else {
          return stack[stackSize-1];
        }
      }
      
      private void encreaseCapasity() {
        capacity *= scaleFactor;
        stack = Arrays.copyOf(stack, capacity);
      }
      
      private boolean shouldEncrease(int nextLength) {
        return capacity <= nextLength;
      }
    
      public boolean isEmpty() {
        return 0 == stackSize;
      }
      
      private void log(String op, int val) {
        if (log) {
          System.out.println(name + "     " + op + ": " + val);
        }
      }
    }
    

    MinStack implementation:

    public class MinStack implements BasicStack {
      
      private BasicStack stackElements = new StackImpl("BASIC STACK", false);
      private BasicStack minElements = new StackImpl("MIN", false);
    
      public void push(int x) {
        if (minElements.isEmpty()) {
          minElements.push(x);
        } else if (x <= minElements.top()) {
          minElements.push(x);
        }
        stackElements.push(x);
      }
    
      public void pop() {
        if (minElements.top() == stackElements.top()) {
          minElements.pop();
        }
        stackElements.pop();
      }
    
      public int top() {
        return stackElements.top();
      }
      
      public int getMin() {
        return minElements.top();
      }
    
      public boolean isEmpty() {
        return stackElements.isEmpty();
      }
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.