java栈的应用:实现括号匹配检测

来源:互联网 发布:单词读音的软件 编辑:程序博客网 时间:2024/06/10 14:43
package stack;/** * 栈的链式存储模型:基于链表作为存储结构实现的,本例通过单链表实现; * 指针top为链表结点引用,始终指向栈顶元素所在的结点; * @author USER * *///节点类class SLnode{private String data;private SLnode next;public SLnode(SLnode next, String data) {this.next = next;this.data = data;}public String getData() {return data;}public SLnode getNext() {return next;}}//单链表实现的栈类public class StackLink {private SLnode top;private int size;public StackLink() {top = null;size = 0;}//入栈public void push(String str) {SLnode p = new SLnode(top, str);//新入栈的结点p的next域指向toptop = p;size++;}//出栈public String pop() {String ch = top.getData();top = top.getNext();size--;return ch;}//查看栈顶结点元素public String peek() {return top.getData();}//栈是否为空public boolean isEmpty() {return size == 0;}//返回栈的大小public int getSize() {return size;}}

package stack;import java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;/** * 利用栈实现括号匹配检测 * 输入:{a[b(c)d]e} * 输出:true * @author USER * */public class StackLinkApp2 {public static void main(String[] args) throws IOException {InputStreamReader isr = new InputStreamReader(System.in);BufferedReader br = new BufferedReader(isr);String string = br.readLine();Boolean output = bracketMatch(string); System.out.println(output);}private static Boolean bracketMatch(String str) {// TODO Auto-generated method stubStackLink stackLink = new StackLink();for (int i = 0; i < str.length(); i++) {char ch = str.charAt(i);switch (ch) {case '{':case '[':case '(':stackLink.push(ch+"");break;case ')':if (!stackLink.isEmpty() && stackLink.pop().equals("(")) {break;}else {return false;}case ']':if (!stackLink.isEmpty() && stackLink.pop().equals("[")) {break;}else {return false;}case '}':if (!stackLink.isEmpty() && stackLink.pop().equals("{")) {break;}else {return false;}default:break;}}if (stackLink.isEmpty()) {return true;}else {return false;}}}


0 0