/**
* 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
最新推荐文章于 2025-08-13 20:32:54 发布
本文介绍了一个简单的Java栈实现,包括基本操作如压栈、弹栈及判断栈空,并通过JUnit进行测试验证其正确性。
1315

被折叠的 条评论
为什么被折叠?



