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


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

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

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

  1. 反转前: www.shouce.ren
  2. 反转后: cc.loohcsc3w.www