MyStack的2个应用
复习栈的两个应用:
单词逆序:
package com.test.data_struct;import java.io.*;import java.util.*;public class MyReverserTest {public static void main(String[] args) {// TODO Auto-generated method stubInputStreamReader isr=new InputStreamReader(System.in);BufferedReader br=new BufferedReader(isr);String input=null;String output=null;while(true){try {System.out.println("请输入单词,回车结束。若无输入直接回车,则程序终止退出。");input=br.readLine();if(input.equals("")){System.exit(0);}MyReverser mr=new MyReverser();output=mr.doReverse(input);System.out.println("倒置后的单词是:"+output);} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}}class MyReverser{private String output="";private Stack s=new Stack();public String doReverse(String input){for(int i=0;i<input.length();i++)s.push(input.charAt(i));while(!s.isEmpty()){output=output+s.pop();}return output;}}?匹配分隔符:
package com.test.data_struct;import java.io.*;import java.util.*;public class MyCheckerTest {/** * @param args */public static void main(String[] args) {// TODO Auto-generated method stubwhile (true) {System.out.println("please input a String,no input means exit:");String input = getString();if (input.equals("")){System.out.println("no input ,exit.");break;}MyChecker mc = new MyChecker();mc.checkSymbol(input);}}public static String getString() {String input = "";InputStreamReader isr = new InputStreamReader(System.in);BufferedReader br = new BufferedReader(isr);try {input = br.readLine();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}return input;}}class MyChecker {private Stack stk;public MyChecker() {stk = new Stack();}public void checkSymbol(String input) {for (int i = 0; i < input.length(); i++) {char c = input.charAt(i);switch (c) {case '(':case '[':case '{':stk.push(c);break;case ')':case ']':case '}':if (!stk.isEmpty()) {char cx = stk.pop().toString().charAt(0);System.out.println(cx);if ((c == ')' && cx != '(') || (c == ']' && cx != '[')|| (c == '}' && cx != '{')) {System.out.println("not match at no." + (i + 1) + " \""+ c + "\".");}} else {System.out.println("error at no." + (i + 1) + " \"" + c+ "\".");}break;default:break;}}if (!stk.isEmpty()) {System.out.println("missing symbol.");}else{System.out.println("good matched.");}}}?通过这2个小应用,对栈的使用有了点小感觉了。