java代码如何使用压栈出栈的方式实现字符串反转呢?

书欣 Java经验 发布时间:2023-01-16 17:48:24 阅读数:10355 1
下文笔者讲述字符串"使用压栈出栈的方式"实现"字符串反转"的方法分享,如下所示
实现思路:
   利用栈的后进先出的方式
   即可实现字符串的反转
例:
 
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.java265.com";
	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);
	}
  }
}
版权声明

本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。

本文链接: https://www.Java265.com/JavaJingYan/202301/16738625435389.html

最近发表

热门文章

好文推荐

Java265.com

https://www.java265.com

站长统计|粤ICP备14097017号-3

Powered By Java265.com信息维护小组

使用手机扫描二维码

关注我们看更多资讯

java爱好者