Last active
September 16, 2020 13:22
-
-
Save romanoffs/5067b30e53c6484ed446ea70ed472f3d to your computer and use it in GitHub Desktop.
Stack Data Structure in Java | push, put -> 0(1)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class CustomStack { | |
private int size; | |
private final int[] arr; | |
public CustomStack(int maxSize) { | |
this.arr = new int[maxSize]; | |
this.size = -1; | |
} | |
public void push(int x) { | |
if (!isFull()) { | |
arr[++size] = x; | |
} | |
} | |
public int pop() { | |
if (!isEmpty()) { | |
return arr[size--]; | |
} | |
return -1; | |
} | |
public void increment(int k, int val) { | |
if (!isEmpty()) { | |
for (int i = 0; i < k && i <= size; i++) { | |
arr[i] += val; | |
} | |
} | |
} | |
private boolean isEmpty() { | |
return size == -1; | |
} | |
private boolean isFull() { | |
return size == arr.length - 1; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment