Created
October 15, 2015 13:35
-
-
Save gcrfelix/09c7cc6ea43818d3f56e to your computer and use it in GitHub Desktop.
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
// Use Arrays | |
import java.util.Arrays; | |
public class MyStackArray<E> { | |
private int size = 0; | |
private static final int DEFAULT_CAPACITY = 10; | |
private Object elements[]; | |
public MyStackArray() { | |
elements = new Object[DEFAULT_CAPACITY]; | |
} | |
public void push(E e) { | |
if (size == elements.length) { | |
ensureCapa(); | |
} | |
elements[size++] = e; | |
} | |
@SuppressWarnings("unchecked") | |
public E pop() { | |
E e = (E) elements[--size]; | |
elements[size] = null; | |
return e; | |
} | |
private void ensureCapa() { | |
int newSize = elements.length * 2; | |
elements = Arrays.copyOf(elements, newSize); | |
} | |
} | |
// Use LinkedList | |
import java.util.ArrayList; | |
public class MyStackList<E> extends ArrayList<E> { | |
private static final long serialVersionUID = 1L; | |
public E pop() { | |
E e = get(size() - 1); | |
remove(size() - 1); | |
return e; | |
} | |
public void push(E e) { | |
add(e); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment