您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息

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

2025/2/18 10:47:41发布16次查看
以下实例演示了使用用户自定义的方法 stringreverserthroughstack() 来实现字符串反转:
/* author by w3cschool.cc stringreverserthroughstack.java */import java.io.ioexception;public class stringreverserthroughstack { private string input; private string output; public stringreverserthroughstack(string in) { input = in; } public string dorev() { int stacksize = input.length(); stack thestack = new stack(stacksize); for (int i = 0; i < input.length(); i++) { char ch = input.charat(i); thestack.push(ch); } output = ""; while (!thestack.isempty()) { char ch = thestack.pop(); output = output + ch; } return output; } public static void main(string[] args) throws ioexception { string input = "www.w3cschool.cc"; string output; stringreverserthroughstack thereverser = new stringreverserthroughstack(input); output = thereverser.dorev(); system.out.println("反转前: " + input); system.out.println("反转后: " + output); } class stack { private int maxsize; private char[] stackarray; private int top; public stack(int max) { maxsize = max; 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); } }}
以上代码运行输出结果为:
反转前: 反转后: cc.loohcsc3w.www
以上就是java 实例 - 压栈出栈的方法实现字符串反转的内容。
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录 Product