码迷,mamicode.com
首页 > 其他好文 > 详细

数据结构之栈的应用

时间:2016-04-04 13:13:37      阅读:197      评论:0      收藏:0      [点我收藏+]

标签:

一、单词逆序

 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 }

二、括号匹配

数据结构之栈的应用

标签:

原文地址:http://www.cnblogs.com/ysw-go/p/5351669.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!