Last active
August 24, 2018 14:22
-
-
Save alfian0/8ef41c3cda5c21e878c38be8a45d6dec to your computer and use it in GitHub Desktop.
This file contains hidden or 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
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); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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