Skip to content

Instantly share code, notes, and snippets.

@ibogun
Created February 22, 2016 16:51
Show Gist options
  • Save ibogun/62795262fa218ce2ff22 to your computer and use it in GitHub Desktop.
Save ibogun/62795262fa218ce2ff22 to your computer and use it in GitHub Desktop.
Stack implementation using arrays
import java.util.EmptyStackException;
public class Stack<Key> implements StackADT<Key> {
public Key[] data; // array-based implementation of the stack
final int INITIAL_SIZE = 8;
int top = 0;
@SuppressWarnings("unchecked")
public Stack() {
data = (Key[]) new Object[INITIAL_SIZE];
}
@SuppressWarnings("unchecked")
public Stack(int n) {
data = (Key[]) new Object[n];
}
@Override
public boolean isEmpty() {
return (top == 0);
}
@Override
public boolean isFull() {
return (top == data.length);
}
@Override
public void push(Key key) {
if (!isFull()) {
this.data[top] = key;
top++;
}
else {
// dynamically reallocate the array
@SuppressWarnings("unchecked")
Key[] dataCopy = (Key[]) new Object[top*2];
for (int i = 0; i < this.data.length; i++) {
dataCopy[i] = data[i];
}
this.data = dataCopy;
push(key);
}
}
@Override
public Key pop() {
if (!isEmpty()) {
Key result = data[top];
top--;
return result;
} {
throw new EmptyStackException();
}
}
@Override
public Key top() {
if (!isEmpty()) {
Key result = data[top];
return result;
} {
throw new EmptyStackException();
}
}
@Override
public String toString() {
StringBuilder sbBuilder = new StringBuilder();
sbBuilder.append("Stack of size: " + this.top +"\n");
for (int i = 0; i < top; i++) {
sbBuilder.append(this.data[i]+" ");
}
return new String(sbBuilder);
}
public static void main(String[] args) {
Stack<Integer> s = new Stack<Integer>();
s.push(21);
s.push(71);
s.push(3);
s.push(8);
System.out.println(s);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment