/* 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 实例 - 压栈出栈的方法实现字符串反转的内容。
