Last active
December 22, 2015 18:09
-
-
Save flour4445/6510629 to your computer and use it in GitHub Desktop.
10分間で作った
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
package net.flourity.lib; | |
import java.util.Arrays; | |
import java.util.NoSuchElementException; | |
public class Stack<E> | |
{ | |
private Object[] elements; | |
private int size; | |
public Stack() | |
{ | |
this(16); | |
} | |
public Stack(int initialCapacity) | |
{ | |
elements = new Object[initialCapacity]; | |
} | |
public void push(E e) | |
{ | |
ensureCapacity(size+1); | |
elements[size++] = e; | |
} | |
public E pop() | |
{ | |
if(size==0) throw new NoSuchElementException(); | |
@SuppressWarnings("unchecked") | |
E res = (E)elements[size-1]; | |
elements[--size] = null; | |
return res; | |
} | |
public E peek() | |
{ | |
if(size==0) throw new NoSuchElementException(); | |
@SuppressWarnings("unchecked") | |
E res = (E)elements[size-1]; | |
return res; | |
} | |
public void ensureCapacity(int minCapacity) | |
{ | |
int oldCapacity = elements.length; | |
if(oldCapacity<minCapacity) | |
{ | |
int newCapacity = oldCapacity << 1; | |
if(newCapacity<minCapacity) newCapacity = minCapacity; | |
elements = Arrays.copyOf(elements, newCapacity); | |
} | |
} | |
public int size() | |
{ | |
return size; | |
} | |
public boolean isEmpty() | |
{ | |
return size==0; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment