您的位置:首页 > 产品设计 > UI/UE

Java ToyProgam LunacyDoctor implements IO and Sequence Stack

2007-06-18 10:57 661 查看
前面写了链栈 http://blog.csdn.net/nyzhl/archive/2007/06/18/1656153.aspx
现在写了个程序实现顺序栈


//Coding by zhaohongliang


import java.io.*;




public class LunacyDoctor ...{




public static void main(String[] args) ...{


BufferedReader sr =new BufferedReader(


new InputStreamReader (System.in) );


String inString = null;


String[] temp = null;




try ...{


inString = sr.readLine();




while(inString!=null) ...{




if(inString.equalsIgnoreCase("exit")) ...{


System.exit(-1);


}


temp = inString.split(" ");


SeqStack<String> ss = new SeqStack<String>(temp.length);




for(String s : temp) ...{


ss.push(s);


}




while(!ss.empty()) ...{


System.out.print(ss.pop()+" ");


}


System.out.println();


inString=sr.readLine();


}


sr.close();


}




catch(IOException e1) ...{


System.out.println("Error:IO Error.");


}




catch(EmptyStackException e2) ...{


System.out.println("Error:Popped an empty Stack.");


}




catch(StackOverFlowException e3) ...{


System.out.println("Error:Stack over flow.");


}


}


}




class SeqStack<T> ...{


private final int size;


private T[] elem;


private int top;




public SeqStack(int size) ...{


this.top = -1;


this.size = size;


elem = (T[])new Object[size];


//elem = new T[size]; 此句JDK会报错:创建泛型数组


}




public boolean empty() ...{


return top==-1 ? true : false ;


}




public boolean full() ...{


return elem.length-1==top ? true : false;


}




public void push(T item) ...{


if(full()) throw new StackOverFlowException();


top ++ ;


elem[top] = item;


}




public T pop() ...{


if(empty()) throw new EmptyStackException();


top -- ;


return elem[top+1];


}




public T peek() ...{


if(empty()) throw new EmptyStackException();


return elem[top];


}


}




class StackOverFlowException extends RuntimeException ...{}




class EmptyStackException extends RuntimeException ...{}


//在java.util包里也有EmptyStackException

可以看出,顺序栈是基于数组的,数组声明时必须声明长度。程序可扩展性差。而且数组的地址空间是固定的。如果强行重新构造数组(ArrayList)将造成写操作执行效率低下。但是数组的地址是可计算的,所以在读写时的效率很高。
而链栈是基于链表的,只要你内存够,就可以无限扩展。但是在读写操作时,要找到目标对象比较耗费资源。但是栈只是针对栈顶操作,就不存在这个问题了。所以我觉得综合来看,还是链栈比较好用。不知道JRE里的栈是怎么实现的。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: