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

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域指向top

top = 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 stub

StackLink 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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值