数据结构之栈的应用
Posted 菜鸟奋斗史
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了数据结构之栈的应用相关的知识,希望对你有一定的参考价值。
一、单词逆序
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 args 65 * @author ysw_go 66 * @throws IOException 67 */ 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 }
二、括号匹配
以上是关于数据结构之栈的应用的主要内容,如果未能解决你的问题,请参考以下文章