栈的数组实现(Java)

来源:互联网 发布:java加载项 编辑:程序博客网 时间:2024/05/22 16:59
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

0 0
原创粉丝点击