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

以下实例演示了使用用户自定义的方法 StringReverserThroughStack() 来实现字符串反转:
转载于http://www.runoob.com/java/data-reverse.html

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);
      }
   }
}

这个例子的内容是先正序将字符串分解成字符压入栈中,然后在取出,由于栈先入后出,后入先出的原理。字符串就会实现反向输出。体现了压栈出栈的过程

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值