栈-单词逆序

来源:互联网 发布:star法则 程序员 编辑:程序博客网 时间:2024/06/14 04:24
package c_stack.B_wordReverse;


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
/**
 * 单词逆序
 * 
 * @author Administrator
 *
 */
public class ReverseApp {
public static void main(String[] args) throws IOException {
String input, output;
while (true) {
System.out.println("Enter a String");
System.out.flush();
input = getString();
if (("").equals(input)) {
break;
}
Reverser reverser = new Reverser(input);
output = reverser.doRev();
System.out.println("Reversed:" + output);
}
}


public static String getString() throws IOException {
String s = new BufferedReader(new InputStreamReader(System.in))
.readLine();
return s;
}


}package c_stack.B_wordReverse;
/**
 * 反转
 * @author Administrator
 *
 */
public class Reverser {
private String input;
private String output;
public Reverser(String in) {
input=in;
}
public String doRev(){
int stackSize=input.length();
WordReverse wordReverse=new WordReverse(stackSize);

for(int i=0;i<stackSize;i++){
char c=input.charAt(i);
wordReverse.push(c);
}
output="";
while(!wordReverse.isEmpty()){
output+=wordReverse.pop();
}
return output;
}


}package c_stack.B_wordReverse;


public class WordReverse {
private int maxSize;
private char[] stackArray;
private int top;


public WordReverse(int max) {
maxSize = max;
stackArray = new char[max];
top = -1;
}
/*
* 锟斤拷栈
*/
public void push(char i){
stackArray[++top]=i;
}
/*
* 锟斤拷栈
*/
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;
}
}
0 0
原创粉丝点击