一、单词逆序
1 package data.struct.algorithm; 2 3 import java.io.BufferedReader; 4 import java.io.IOException; 5 import java.io.InputStreamReader; 6 7 //以数组为内核实现栈 8 class Stacky { 9 private int maxSize;10 private char[] stackArray;11 private int top;12 13 public Stacky(int s) {14 maxSize = s;15 stackArray = new char[maxSize];16 top = -1;17 }18 19 public void push(char value) {20 stackArray[++top] = value;21 }22 23 public char pop() {24 return stackArray[top--];25 }26 27 public char peek() {28 return stackArray[top];29 }30 31 public boolean isEmpty() {32 return top == -1;33 }34 }35 36 // 定义Reverse类实现字符串逆序37 class Reverse {38 private String input;39 private String output;40 41 public Reverse(String input) {42 this.input = input;43 }44 45 public String doRev() {46 int size = input.length();47 Stacky theStacky = new Stacky(size);48 for (int x = 0; x < input.length(); x++) {49 char ch = input.charAt(x);50 theStacky.push(ch);51 }52 output = "";53 while (!theStacky.isEmpty()) {54 output = output + theStacky.pop();55 }56 return output;57 58 }59 }60 61 public class StackApp2 {62 63 /**64 * @param args65 * @author ysw_go66 * @throws IOException67 */68 // 用栈实现单词逆序69 public static void main(String[] args) throws IOException {70 71 String input, output;72 while (true) {73 System.out.println("please input a string:");74 input = getString();75 if (input.equals("")) {76 break;77 }78 Reverse reverse = new Reverse(input);79 output = reverse.doRev();80 System.out.println("Reversed:" + output);81 }82 }83 84 // 定义方法从键盘获取输入的字符串85 public static String getString() throws IOException {86 BufferedReader bufr = new BufferedReader(new InputStreamReader(87 System.in));88 return bufr.readLine();89 90 }91 }
二、括号匹配
1 package data.struct.algorithm; 2 3 import java.io.BufferedReader; 4 import java.io.IOException; 5 import java.io.InputStreamReader; 6 7 import javax.swing.DefaultBoundedRangeModel; 8 9 //以数组为内核实现栈 10 class Stackz { 11 private int maxSize; 12 private char[] stackArray; 13 private int top; 14 15 public Stackz(int s) { 16 maxSize = s; 17 stackArray = new char[maxSize]; 18 top = -1; 19 } 20 21 public void push(char value) { 22 stackArray[++top] = value; 23 } 24 25 public char pop() { 26 return stackArray[top--]; 27 } 28 29 public char peek() { 30 return stackArray[top]; 31 } 32 33 public boolean isEmpty() { 34 return top == -1; 35 } 36 } 37 class BracketChecker{ 38 private String input; 39 public BracketChecker(String s){ 40 input=s; 41 } 42 public void check(){ 43 Stackz theStackz=new Stackz(input.length()); 44 for(int x=0;x