Skip to content

Instantly share code, notes, and snippets.

@ishikawa
Created September 11, 2008 10:05
Show Gist options
  • Select an option

  • Save ishikawa/10202 to your computer and use it in GitHub Desktop.

Select an option

Save ishikawa/10202 to your computer and use it in GitHub Desktop.
Stack
/**
* http://en.wikipedia.org/wiki/Stack_(data_structure)
*/
public class Stack <E> {
private LinkedList<E> elements = new LinkedList<E>();
public int size() { return elements.size(); }
public boolean isEmpty() { return elements.isEmpty(); }
public E top() { return elements.get(0); }
public E pop() { return elements.removeFirst(); }
public void push(E element) { elements.addFirst(element); }
}
import junit.framework.TestCase;
public class StackTest extends TestCase {
public void test_empty() {
Stack<?> stack = new Stack<Object>();
assertNotNull(stack);
assertTrue(stack.isEmpty());
assertEquals(0, stack.size());
}
public void test_simple() {
Stack<Integer> stack = new Stack<Integer>();
stack.push(1);
stack.push(2);
stack.push(3);
assertFalse(stack.isEmpty());
assertEquals(3, stack.size());
assertEquals(new Integer(3), stack.top());
assertEquals(3, stack.size());
assertEquals(new Integer(3), stack.pop());
assertEquals(2, stack.size());
assertEquals(new Integer(2), stack.pop());
assertEquals(1, stack.size());
assertEquals(new Integer(1), stack.pop());
assertEquals(0, stack.size());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment