1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74
| class Stack_Char{ private int maxSize; //栈的长度 private char[] stackArray; //创建栈的数组的引用 private int top; //创建栈顶的引用 public Stack_Char(int s) { //构造函数 this.maxSize = s; stackArray = new char[maxSize]; //创建对象 top = -1; //栈顶等于-1 } public void push(char j){ //入栈操作 stackArray[++top] = j; //先把top=-1自加成0,再入栈 } public char pop(){ return stackArray[top--]; //弹出当前栈顶的元素后,再自减 } public char peek(){ return stackArray[top]; //返回当前栈顶的元素 } public boolean isEmpty(){ //栈顶为-1,即栈为空 return (top == -1); } public boolean isFull(){ //栈顶为maxSize-1,即栈为满 return (top == maxSize-1); } }
class Reverse{ private String input; private String output; public Reverse(String input) { //构造函数 super(); this.input = input; } public String DoReverse(){ int stackSize = input.length(); Stack_Char stack_demo = new Stack_Char(stackSize); for(int i=0;i<stackSize;i++){ //把每一个字母入栈 char ch = input.charAt(i); stack_demo.push(ch); } output = ""; //给output赋值,否则会变成nullXXX while( !stack_demo.isEmpty() ){ //把每一个字母出栈 char ch = stack_demo.pop(); this.output += ch; } return this.output; } }
public class Word_Reverse {
public static void main(String[] args) { // TODO 自动生成的方法存根 String input,output; input = "part"; System.out.println("输入的字符串:"+input); Reverse rev = new Reverse(input); output = rev.DoReverse(); System.out.println("输出的字符串:"+output); }
}
|