Java 实例 - 压栈出栈的方法实现字符串反转
以下实例演示了使用用户自定义的方法 StringReverserThroughStack() 来实现字符串反转:
StringReverserThroughStack.java 文件
importjava.io.IOException;
publicclassStringReverserThroughStack{privateStringinput;
privateStringoutput;
publicStringReverserThroughStack(Stringin){input = in;
}publicStringdoRev(){intstackSize = input.length();
StacktheStack = newStack(stackSize);
for(inti = 0; i < input.length(); i++){charch = input.charAt(i);
theStack.push(ch);
}output = "";
while(!theStack.isEmpty()){charch = theStack.pop();
output = output + ch;
}returnoutput;
}publicstaticvoidmain(String[]args)throwsIOException{Stringinput = "www.w3cschool.cc";
Stringoutput;
StringReverserThroughStacktheReverser =
newStringReverserThroughStack(input);
output = theReverser.doRev();
System.out.println("反转前: " + input);
System.out.println("反转后: " + output);
}classStack{privateintmaxSize;
privatechar[]stackArray;
privateinttop;
publicStack(intmax){maxSize = max;
stackArray = newchar[maxSize];
top = -1;
}publicvoidpush(charj){stackArray[++top] = j;
}publiccharpop(){returnstackArray[top--];
}publiccharpeek(){returnstackArray[top];
}publicbooleanisEmpty(){return(top == -1);
}}}
以上代码运行输出结果为:
反转前: www.w3cschool.cc 反转后: cc.loohcsc3w.www