Skip to content

Instantly share code, notes, and snippets.

@alfian0
Last active August 24, 2018 14:22
Show Gist options
  • Save alfian0/8ef41c3cda5c21e878c38be8a45d6dec to your computer and use it in GitHub Desktop.
Save alfian0/8ef41c3cda5c21e878c38be8a45d6dec to your computer and use it in GitHub Desktop.
public class Stack {
private Object[] elements;
private int size = 0;
private static final int DEFAULT_INITIAL_CAPACITY = 16;
public Stack() {
elements = new Object[DEFAULT_INITIAL_CAPACITY];
}
public void push(Object e) {
ensureCapacity();
elements[size++] = e;
}
public Object pop() {
if (size == 0)
throw new EmptyStackException();
return elements[--size];
}
/**
* Ensure space for at least one more element, roughly
* doubling the capacity each time the array needs to grow.
*/
private void ensureCapacity() {
if (elements.length == size)
elements = Arrays.copyOf(elements, 2 * size + 1);
}
}
@alfian0
Copy link
Author

alfian0 commented Aug 24, 2018

return elements[--size] at line 18 will return last element but we are not poping elements, element size still same, we need set last element to null

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment