Java ToyProgam LunacyDoctor implements IO and Sequence Stack

前面写了链栈 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里的栈是怎么实现的。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值