/** * Introduction to Algorithms, Second Edition * 10.1 Stacks * @author 土豆爸爸 * */ import java.util.EmptyStackException; public class Stack { private int[] array; private int top = -1; /** * 构造函数,创建一个可以容纳size个元素的栈 * @param size 栈的大小 */ public Stack(int size) { array = new int[size]; } /** * 判断栈是否为空 * @return 栈是否为空 */ public boolean isEmpty() { return top == -1; } /** * 将元素x压栈。压栈后栈顶指针加1。 * @param x 待入栈元素 */ public void push(int x) { if(top == array.length -1) { throw new RuntimeException("Overflow"); } array[++top] = x; } /** * 弹出栈顶元素。出栈后栈顶指针减1。 * @return */ public int pop() { if(isEmpty()) { throw new EmptyStackException(); } return array[top--]; } } import java.util.EmptyStackException; import junit.framework.TestCase; public class StackTest extends TestCase { public void testStack() { Stack s = new Stack(10); s.push(1); s.push(2); s.push(3); assertEquals(3, s.pop()); assertEquals(2, s.pop()); assertFalse(s.isEmpty()); s.push(4); s.push(5); assertEquals(5, s.pop()); assertEquals(4, s.pop()); assertEquals(1, s.pop()); assertTrue(s.isEmpty()); try{ s.pop(); fail("pop应抛出异常"); } catch(Exception e) { assertTrue(e instanceof EmptyStackException); } } }
算法导论示例-Stack
最新推荐文章于 2024-07-26 13:30:36 发布