-
-
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
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
/** | |
* 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