TestStackOfInteger

public class TestStackOfInteger {
    public static void main(String[] args) {
        StackOfInteger stack = new StackOfInteger(0);
       
        for(int i = 0; i < 10; i++)
            stack.push(i);
       
        System.out.println(stack.getSize());
       
        while(!stack.empty())
            System.out.print(stack.pop() + " ");
        System.out.println();
    }

}



/**栈(stack)是一种以“后进先出”的方式存放数据的数据结构
 * 栈的应用有很多。例如:编译器使用栈来处理方法的调用。当调用某个方法时
 * 方法的参数和局部变量都被压入栈中。当一个方法调用另一个方法时,
 * 新方法的参数和局部变量被压入栈中。当方法完成它的工作,返回它的调用者时,
 * 从栈中释放与它相关的空间
 */



public class StackOfInteger {
    private int[] elements;
    private int size = 0;
   
    /** Construct a stack with the default capacity 16 */
    public StackOfInteger() {
        this(16);
    }
   
    /** Construct a stack with the capacity */
    public StackOfInteger(int capacity) {
        if(capacity < 0)
            capacity = 0;
        elements = new int[capacity];
    }
   
    /** Push a new integer into the top of the stack */
    public void push(int value) {
        if(elements.length == size) {
            int[] newElements = new int[elements.length * 2 + 1];
            for(int i = 0; i < size; i++)
                newElements[i] = elements[i];
            elements = newElements;
        }
        elements[size++] = value;
    }
   
    /** Return and remove the top element from the stack */
    public int pop() {
        return elements[--size];
    }
   
    /** Return the top element frome the stack */
    public int peek() {
        return elements[size - 1];
    }
   
    /** Test whether the stack is empty */
    public boolean empty() {
        return size==0;
    }
   
    /** Return the number of elements in the stack */
    public int getSize() {
        return size;
    }
   
    /** Return the capacity of elements in the stack */
    public int getCapacity() {
        return elements.length;
    }
}






10
9 8 7 6 5 4 3 2 1 0


  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值