栈的数组实现(Java)

package com.Stack;

public class ArrayStack <AnyType>{
	public ArrayStack(){
			theArray = (AnyType [])new Object[DEFAULT_CAPACITY];
			topOfStack = -1;
		};
	public boolean isEmpty(){
		return topOfStack == -1;
	}
	public void makeEmpty(){
		topOfStack = -1;
	}
	public AnyType top(){
		try {
		if(isEmpty())		
				throw  new Exception("ArrayStack top");
			} 
		catch (Exception e) {
				e.printStackTrace();
			}
		return theArray[topOfStack];
	}
	public void pop(){
			if(isEmpty()){
				//抛出异常
			}
			topOfStack--;	
	}
	public AnyType topAndPop(){
		if(isEmpty()){
			//....
		}
		return theArray[topOfStack--];
//		AnyType data = theArray[topOfStack];
//		topOfStack--;
//		return data;
	}
	public void push(AnyType x){
		if(topOfStack+1 == theArray.length){
			//doubleArray();
			
		}
		theArray[++topOfStack] = x;
	}
	/*
	 * 数组加倍
	 */
	private void doubleArray(){
		
	}
	private int topOfStack;
	private AnyType[] theArray;
	private static final int DEFAULT_CAPACITY = 10;
}

测试类:

package com.Stack;

public class testArrayStack {
	@SuppressWarnings("unchecked")
	public static void main(String[] args){
		ArrayStack stack = new ArrayStack();
		String[] data = new String[]{"a","b","c"};
		for(int i = 0;i < data.length;i++){
			stack.push(data[i]);
			System.out.println(data[i]+" ");
		}
		System.out.println("*************************");
		while(!stack.isEmpty()){
			System.out.println(stack.topAndPop()+"");
		}
	}
}

输出结果:




*************************
c
b
a

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值