菜鸟教程 -- 学的不仅是技术,更是梦想!

Java 教程
(追記) (追記ここまで)

Java 实例 - 压栈出栈的方法实现字符串反转

Java 实例 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

Java 实例 Java 实例

AI 思考中...

点我分享笔记

  • 昵称 (必填)
  • 邮箱 (必填)
  • 引用地址

AltStyle によって変換されたページ (->オリジナル) /