下面来看一个程序,StackX.javapublicclassStackX<T>{privateint maxSize;// size of stack arrayprivateObject[] stackList;privateint top;// top of stackpublicStackX(int maxSize){// constructorthis.maxSize = maxSize;// set array size stackList =newObject[maxSize];// create array top =-1;// no items yet}publicsynchronized void push(T data){// put item on top of stack stackList[++top]= data;// increment top, insert item}@SuppressWarnings("unchecked")public synchronizedT pop(){// take item from top of stackreturn(T) stackList[top--];// access item, decrement top}@SuppressWarnings("unchecked")publicsynchronized T peek(){// peek at top of stackreturn(T) stackList[top];}publicsynchronized boolean isFull(){// true if stack is fullreturn top == maxSize-1;}publicsynchronizedboolean isEmpty(){// true if stack is emptyreturn top ==-1;}}
StackTest.java
publicclassStackTest{publicstaticvoid main(String[] args)throwsIOException{int[] datas ={1,2,3,4};StackX<Integer> stackX =newStackX<Integer>(4);for(int i=0; i<datas.length; i++){ stackX.push(datas[i]);}while(!stackX.isEmpty()){System.out.print(stackX.pop());System.out.print(" ");}}publicstaticString getString()throwsIOException{InputStreamReader isr =newInputStreamReader(System.in);BufferedReader br =newBufferedReader(isr);String line = br.readLine();return line;}}
输出结果如下:
4321 请注意显示数据的顺序和输入的顺序正好相反。这是因为最后入栈的数据项最先弹出,所以输出结果中4显示在最前面。