Created
September 11, 2008 10:05
-
-
Save ishikawa/10202 to your computer and use it in GitHub Desktop.
Stack
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
| /** | |
| * 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); } | |
| } | |
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
| 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