Skip to content

Instantly share code, notes, and snippets.

@flour4445
Last active December 22, 2015 18:09
Show Gist options
  • Save flour4445/6510629 to your computer and use it in GitHub Desktop.
Save flour4445/6510629 to your computer and use it in GitHub Desktop.
10分間で作った
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