栈的应用--栈用作判断平衡符号,[()]对的,[(])错的
2015-07-02 14:42
393 查看
#include<stdio.h> #include<stdlib.h> struct Node; typedef struct Node *PtrToNode; typedef PtrToNode Stack; struct Node{ char Ele; PtrToNode Next; }; Stack CreateStack( void ) { Stack S; S = malloc( sizeof( struct Node ) ); if(S == NULL ) printf("out of space"); S->Next = NULL; return S; } void Push(char ch,Stack S) { PtrToNode TmpCell; TmpCell = malloc(sizeof( struct Node )); if(TmpCell == NULL) printf("out of space "); else { TmpCell->Next = S->Next; S->Next = TmpCell; TmpCell->Ele = ch; } } int IsEmpty(Stack S) { return S->Next == NULL; } void Pop( Stack S ) { PtrToNode TmpCell; TmpCell = S->Next; S->Next = TmpCell->Next; free(TmpCell); } char Top( Stack S ) { return S->Next->Ele; } int main() { char Tmp; Stack S; S = CreateStack(); while( ( Tmp = getchar() ) != '\n' ) { if(Tmp == '[' || Tmp == '(') Push(Tmp,S); else if(Tmp == ']') { if( !IsEmpty( S ) ) { char tmp; tmp = Top( S ); Pop( S ); if(tmp != '[') printf("error"); } else printf("Error"); }//else if else { if( !IsEmpty( S ) ) { char tmp; tmp = Top( S ); Pop( S ); if(tmp != '(') printf("error"); } else printf("error"); }//else } if( !IsEmpty( S )) printf("error"); return 0; }
View Code
算法描述:如果遇到开放符号就进栈,如果遇到封闭符号,先判断此时是不是空栈,是就报错,否则,就出栈判断是否是其对应的开放符号,不是就报错,如果读到文件结尾,栈不为空,报错
相关文章推荐
- background-size 导致的背景不居中问题
- node.js学习笔记之常用模块介绍
- WinCE下串口蓝牙模块的调试
- 几种常见加密算法初窥及如何选用加密算法
- php 5.6.10V11 apache 2.4.12 V14配置
- oracle游标
- [Android]Intent 实现页面跳转的方式[转]
- 关于对inputstream流的复制
- Linux磁盘相关和MBR
- Android Studio中文乱码的解决
- IME被禁用
- oracle的for update
- PHP获取IP的方法对比
- ES6新特性概览
- GCD 术语 串行 vs. 并发 同步 vs. 异步
- 一个处理用户登陆的servlet简单实例
- 黑马程序员--OC学习笔记之代理模式的简单分析
- PHP中MySql函数收集
- samba配置(z)
- 多态