Skip to content

Instantly share code, notes, and snippets.

@sricharankrishnan
Last active April 12, 2023 04:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sricharankrishnan/2c1637d5c93578227eff8b0eae832d83 to your computer and use it in GitHub Desktop.
Save sricharankrishnan/2c1637d5c93578227eff8b0eae832d83 to your computer and use it in GitHub Desktop.
A stack (array style) data structure implementation done in java along with respective time complexities for each method
/**
* Array Stack Java Implementation
* public void push(E value): O(1)
* public E peek(): O(1)
* public E pop(): O(1)
*/
import java.util.Objects;
public class ArrayStack<E> {
private int top;
private Object[] stack;
public ArrayStack(final int n) throws Exception {
if (n < 1) {
throw new Exception("Cannot Initialize. Capacity to be greater than zero");
}
this.stack = new Object[n];
this.top = -1;
}
public void push(final E obj) {
if (!this.isFull() && !Objects.isNull(obj)) {
this.stack[++this.top] = obj;
}
}
public E peek() {
return (E)(this.isEmpty() ? null : this.stack[this.top]);
}
public void pop() {
if (!this.isEmpty()) {
this.stack[this.top--] = null;
}
}
public boolean isFull() {
return this.size() == this.stack.length;
}
public boolean isEmpty() {
return this.size() == 0;
}
public int size() {
return this.top + 1;
}
@Override
public String toString() {
String string = "[";
if (!this.isEmpty()) {
for (int i = this.size() - 1; i >= 0; --i) {
string += (i == 0) ? this.stack[i] : this.stack[i] + " --> ";
}
}
return string += "]";
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment