算法导论示例-Stack

/**
 * 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);
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值