栈
来源:互联网 发布:淘宝店铺怎么设置客服 编辑:程序博客网 时间:2024/06/04 19:26
public class StackX { /* 栈遵后进先出的原则,top索引记录栈顶位置,入栈push,弹出栈pop 是否满ifFull,是否为空ifEmpty,查看栈顶对象peek。 */ private Object[] obj; private int top; private int maxSize; public StackX() {} public StackX(int maxSize) { this.maxSize = maxSize; top = -1; obj = new Object[maxSize]; } public void push(Object value) { obj[++top] = value; } public Object pop() { return obj[top--]; } public Object peek() { return obj[top]; } public boolean isEmpty() { return top == -1; } public boolean isFull() { return top == (maxSize - 1); } //栈应用1:到此逆序,输出"abc",输出"cba" public String wordReverse(String word) { String str = ""; StackX stackX = new StackX(word.length()); for (int i = 0; i < word.length(); i++) { stackX.push(word.charAt(i)); } while (!stackX.isEmpty()) { char pop = (char)stackX.pop(); str += pop; } return str; } //栈应用2:符号匹配,主要进行{}[]()这几种符号的匹配,可以用来检测表达式是否缺少括号。 public void check(String expr) { StackX stackX = new StackX(expr.length()); for (int i = 0; i < expr.length(); i++) { char c = expr.charAt(i); switch (c) { case '[': case '{': case '(': stackX.push(c); break; case ']': case '}': case ')': if(!stackX.isEmpty()) { char c1 = (char)stackX.pop(); if(c == '}' && c1 != '{' || c == ']' && c1 != '[' || c == ']' && c1 != '[') { System.out.println("error:" + c + "\tindex at\t" + i); } } else { System.out.println("error:" + c + "\tindex at\t" + i); } break; default: break; } } if(!stackX.isEmpty()) System.out.println("error:missing delimiter"); } public static void main(String[] args) { StackX stackX = new StackX(); String s = stackX.wordReverse("abc"); System.out.println(s); //cba stackX.check("a{b[csd(af]}"); /* error:]index at10 error:}index at11 error:missing delimiter */ }}
阅读全文
0 0
- 栈
- 栈
- 栈
- 栈
- 栈
- 栈
- 栈
- 栈
- 栈
- 栈
- 栈
- 栈
- 栈
- 栈
- 栈
- 栈
- 栈
- 栈
- 微信联系人列表点击侧边栏首字母定位到相应联系人列表的实现方法
- Kotlin汇总1
- 串并转换verilog程序
- USACO-Section 1.3 Barn Repair[...]
- 转载“克鲁斯卡尔算法的详解”
- 栈
- 现在看到这里
- 1011. A+B和C (15)
- SAP UI5的HTML调用view报错500
- mybatis传多个参数(不使用@param注解情况下),3.4.2版本之后使用#{0}-#{n}引起的参数绑定异常,以及settings属性中useActualParamName的作用。
- 深度学习权重初始化的原则
- 解决wordpress 更新翻译提示更新成功了,但是刷新一下又提示的问题
- Codechef Consecutive Snakes(三分)
- USACO-Section1.2 Name That Number