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

以下实例演示了使用用户自定义的方法 StringReverserThroughStack() 来实现字符串反转:

StringReverserThroughStack.java 文件

  1. import java.io.IOException;
  2. public class StringReverserThroughStack {
  3. private String input;
  4. private String output;
  5. public StringReverserThroughStack(String in) {
  6. input = in;
  7. }
  8. public String doRev() {
  9. int stackSize = input.length();
  10. Stack theStack = new Stack(stackSize);
  11. for (int i = 0; i < input.length(); i++) {
  12. char ch = input.charAt(i);
  13. theStack.push(ch);
  14. }
  15. output = "";
  16. while (!theStack.isEmpty()) {
  17. char ch = theStack.pop();
  18. output = output + ch;
  19. }
  20. return output;
  21. }
  22. public static void main(String[] args)
  23. throws IOException {
  24. String input = "www.baidu.com";
  25. String output;
  26. StringReverserThroughStack theReverser =
  27. new StringReverserThroughStack(input);
  28. output = theReverser.doRev();
  29. System.out.println("反转前: " + input);
  30. System.out.println("反转后: " + output);
  31. }
  32. class Stack {
  33. private int maxSize;
  34. private char[] stackArray;
  35. private int top;
  36. public Stack(int max) {
  37. maxSize = max;
  38. stackArray = new char[maxSize];
  39. top = -1;
  40. }
  41. public void push(char j) {
  42. stackArray[++top] = j;
  43. }
  44. public char pop() {
  45. return stackArray[top--];
  46. }
  47. public char peek() {
  48. return stackArray[top];
  49. }
  50. public boolean isEmpty() {
  51. return (top == -1);
  52. }
  53. }
  54. }

以上代码运行输出结果为:

  1. 反转前: www.baidu.com
  2. 反转后: moc.udiab.www