用自定义栈去实现字符串反转
程序员文章站
2024-01-24 11:13:34
...
package date0610; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; /** *@author TonyJ *@time 2011-6-10 下午03:46:08 */ public class Test02 { private char arr[]; private int maxSize; private int top; public Test02(int s) { arr = new char[s]; top = -1; maxSize = s; } public void push(char c) {//进栈 arr[++top] = c; } public char pull() {//出栈 return arr[top--]; } public char peek() {//取得栈头数据 return arr[top]; } public boolean isEmpty() {//判断是否空 return top == -1; } public boolean isFull() {//判断栈是否已满 return top == maxSize - 1; } public static String getString() {//获得输入的字符串 String str = null; BufferedReader br = null; br = new BufferedReader(new InputStreamReader(System.in)); try { System.out.println("请输入字符串:"); str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } public static String reverse() { String input = getString(); String output=""; Test02 t = new Test02(input.length()); for (int i = 0; i < input.length(); i++) { t.push(input.charAt(i)); } while (!t.isEmpty()) { output =output+ t.pull(); } return output; } public static void main(String[] args) { System.out.println(reverse()); } }