栈的变相面试题:(将字符串逆序)
写一个算法,将字符串逆序
import java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;public class ReverseApp{ public static void main(String args[]) throws IOException{ String input,output; while(true){ System.out.print("请输入一个字符串"); System.out.flush(); input=getString(); if(input.equals(" ")){ break; } Reverser theReverser=new Reverser(input); output=theReverser.doRev(); System.out.println("反转后是"+output);}}public static String getString()throws IOException{InputStreamReader isr=new InputStreamReader(System.in);BufferedReader br=new BufferedReader(isr);String s=br.readLine();return s;}}class Reverser{private String input;private String output;public Reverser(String in){input=in;}//执行反转public String doRev(){int stackSize=input.length();Stackx theStack = new Stackx(stackSize);for(int j=0; j<input.length();j++){char ch=input.charAt(j);theStack.push(ch);}output=" ";while(!theStack.isEmpty()){char ch=theStack.pop();output=output+ch;}return output;}}//栈 class Stackx{//三个必须元素private int maxSize;private char[] stackArray;private int top;//构造栈public Stackx(int s){ maxSize=s; stackArray=new char[maxSize]; 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);}}
?
/** * 字符串反转(栈) * * @param str * @return */public String reverseStr(String str) {char[] stack = new char[str.length()];// 栈// 进栈for (int i = 0; i < str.length(); i++) {stack[i] = str.charAt(i);}// 出栈StringBuffer reverseStr = new StringBuffer("");for (int j = stack.length - 1; j >= 0; j--) {reverseStr.append(stack[j]);}return reverseStr.toString();}/** * 字符串反转(递归) * * @param str * @return */public static String recursionReverseStr(String str) {int i = str.length();if (i < 1) {return "";} else {return str.charAt(--i) + recursionReverseStr(str.substring(0, i));}} 13 楼 whaosoft 2009-09-16 没遇到这种面试题