java 栈

先进后出


public class MyStack {
	
	private int maxSize;
	private long arr [];
	private int top;
	
	public MyStack(int maxSize) {
		this.maxSize = maxSize;
		arr = new long [maxSize] ;
		top = -1;
	}
	
	/**
	 * 压入数据
	 * @param value
	 */
	public void push(long value) {
		arr [++ top] = value;
	}
	
	/**
	 * 弹出数据
	 * @return
	 */
	public long pop () {
		return arr [top--];
	}
	
	/**
	 * 访问栈顶数据
	 * @return
	 */
	public long peek() {
		return arr[top];
	}
	
	/**
	 * 判断是否为空
	 * @return
	 */
	public boolean isEmpty() {
		return (top == -1);
	}
	
	/**
	 * 判断是否满了
	 * @return
	 */
	public boolean isFull() {
		return (top == (maxSize -1));
	}
} 


测试:


public class MyStackTest {
    
    public static void main(String[] args) {
        MyStack myStack = new MyStack(6);
        System.out.println("是否为空:" + myStack.isEmpty());
        
        myStack.push(50);
        myStack.push(40);
        myStack.push(30);
        myStack.push(20);
        myStack.push(10);
        myStack.push(0);
        
        while(!myStack.isEmpty()) {
            System.out.println(myStack.pop());
        }
        
        System.out.println("是否为空:" + myStack.isEmpty());
        System.out.println("是否满了:" +myStack.isFull());
        
        
        myStack.push(500);
        myStack.push(400);
        myStack.push(300);
        myStack.push(200);
        myStack.push(100);
        myStack.push(0);
        
        while(!myStack.isEmpty()) {
            System.out.println(myStack.pop());
        }
        
    }

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值