使用栈判断输入的表达式中括号是否配对
2015-11-10 15:14
267 查看
import java.util.Scanner; class LStack { class Node { char data; Node next; } Node head; public LStack() { head = new Node(); } // 进栈 // 其实就是头插法建表,把结点插在头结点和原栈顶结点之间,并将此结点变为栈顶结点 public void Push(char data) { Node n = new Node(); n.data = data; n.next = head.next; head.next = n; } // 出栈 public char Pop() { Node n = new Node(); if (head.next == null) return 0; char a = head.next.data; head.next = head.next.next; return a; } // 显示栈中元素 public void DispStack() { Node n = head.next; while (n != null) { System.out.print(n.data + " "); n = n.next; } System.out.println(); } // 获取栈顶元素 public char GetTop() { if (head.next == null) return 0; else return head.next.data; } // 获取栈的长度 public int StackLength() { int l = 0; Node n = head.next; while (n != null) { l++; n = n.next; } return l; } } public class MyLStack { public static void main(String args[]) { Scanner cin = new Scanner(System.in); String str = cin.nextLine(); System.out.println(Match(str)); } public static boolean Match(String str) { LStack ls = new LStack(); for (int i = 0; i < str.length(); i++) { if (str.charAt(i) == '(') ls.Push('('); else if (str.charAt(i) == ')') { if (ls.GetTop() == '(') ls.Pop(); else return false; } } if (ls.StackLength() == 0) return true; else return false; } }
相关文章推荐
- Android Fragment 生命周期图
- 中文依存句法分析概述及应用
- Android权限之sharedUserId和签名
- Linux编译部署vsftp服务
- Centos7下卸载docker
- 小米开源便签Notes-源码研究(1)-导出功能整体思路
- 小米开源便签Notes-源码研究(1)-导出功能整体思路
- 小米开源便签Notes-源码研究(1)-导出功能整体思路
- (转)PHP AES256加密算法
- mac下 使用sed 将分号替换为回车
- 定时执行Timer
- selenium webdriver+java(test类模板)
- augustus, gene prediction, trainning
- 简单几何(数学公式+凸包) UVA 11168 Airport
- JAVA编程规范
- boost锁的概述
- spring事务配置
- C语言中printf格式详解
- yii2 内部类的列表
- 把 MultiWii 移植到arduino-due中