Skip to content

Instantly share code, notes, and snippets.

@trplll
Created August 16, 2017 03:36
Show Gist options
  • Save trplll/9db21f66d5d160162f23638c6d5dbdfa to your computer and use it in GitHub Desktop.
Save trplll/9db21f66d5d160162f23638c6d5dbdfa to your computer and use it in GitHub Desktop.
Basic java Stack
public class BasicStack<X> {
private X[] data;
private int stackPointer;
public BasicStack() {
data = (X[]) new Object[1000];
stackPointer = 0;
}
public void push(X newItem) {
data[stackPointer++] = newItem;
}
public X pop() {
if (stackPointer == 0) {
throw new IllegalStateException("No more items in the stack");
}
return data[--stackPointer];
}
public boolean contains(X item) {
boolean found = false;
;
for (int i = 0; i < stackPointer; i++) {
if (data[i].equals(item)) {
found = true;
break;
}
}
return found;
}
public X access(X item) {
while (stackPointer > 0) {
X tmpItem = pop();
if (item.equals(tmpItem)) {
return tmpItem;
}
}
throw new IllegalStateException("Could not find this item on the stack: " + item);
}
public int size() {
return stackPointer;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment