栈应用实例-单词逆序

package com.study.dataStructure.linearList;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

//栈类
public class StackX {
    private int maxSize;
    private char[] stackArray;
    private int top;
    
    public StackX(int max){
        stackArray = new char[max];
        top = -1;//空栈
    }
    
    public void push(char j){
        stackArray[++top] = j;
    }
    
    public char pop(){
        return stackArray[top--];
    }
    
    public char peek(){
        return stackArray[top];
    }
    
    public boolean isEmpty(){
        return top == -1;
    }
    
    public boolean isFull(){
        return top == (maxSize -1);
    }
    
}

//倒转字符串类
class Reverse{
    private String input;
    private String output;
    
    public Reverse(String in){
        input = in;
    }
    
    //倒转字符串
    public String doRev(){
        int stackSize = input.length();
        StackX theStack = new StackX(stackSize);
        
        for(int i=0; i< stackSize; i++){
            theStack.push(input.charAt(i));
        }
        
        output = "";
        while(!theStack.isEmpty()){
            output += theStack.pop();
        }
        return output;
    }
}
package com.study.dataStructure.linearList;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

//字符串反转应用
class ReverseApp{
    public static void main(String[] args) throws IOException{
        String input,output;
        
        while(true){
            System.out.println("请输入字符串");
            input = getString();
            if(input.equals("\r")) break;
            
            Reverse theReverser = new Reverse(input);
            output = theReverser.doRev();
            System.out.println("Reversed:"+output);
        }
        
        
    }
    
    public static String getString() throws IOException{
        InputStreamReader isr = new InputStreamReader(System.in);
        BufferedReader br = new BufferedReader(isr);
        String str = br.readLine();
        return str;
    }
}

 

posted @ 2013-01-24 15:19  tangrongyue  Views(315)  Comments(0Edit  收藏  举报