通过栈实现括号匹配
来源:互联网 发布:应力应变数据记录器 编辑:程序博客网 时间:2024/05/21 10:53
首先输入一个待匹配的括号序列,如果是左括号将其压入栈中,如果是右括号则与当前栈顶的括号相匹配(左中括号匹配右中括号,左小括号匹配右小括号)。
若匹配失败,输出匹配失败,程序结束,若匹配成功,将栈顶括号出栈,直到最后一个括号匹配完成。
若最后栈为空输出匹配成功,不为空输出匹配失败。
#include <iostream>#include <string>#define MaxSize 100using namespace std;typedef char ElemType;typedef struct{ ElemType data[MaxSize]; int top;}SqStack;//栈顶指针指向栈顶元素void InitStack(SqStack *st) //初始化栈{ st->top=-1;//}int StackEmpty(SqStack *st) //判断栈为空{ return (st->top==-1);}void Push(SqStack *st,ElemType x) //元素进栈{ if(st->top==MaxSize-1)//判断栈溢出 { printf("栈上溢出!\n"); } else { st->top++; //移动栈顶位置 st->data[st->top]=x; //元素进栈 }}void Pop(SqStack *st,ElemType *e) //出栈{ if(st->top==-1) { printf("栈下溢出\n"); } else { *e=st->data[st->top]; //元素出栈 st->top--; //移动栈顶位置 }}int main(){ SqStack L; SqStack *st=&L; ElemType e; string brackets; int i, n, count = 0;//n表示待检验括号的长度 InitStack(st); //scanf("%d",&n); //scanf("%s",&brackets); cin>>brackets; while(count <= brackets.length()) { if(brackets[count] == '[' || brackets[count] == '(') { //printf("%c\n", brackets); Push(st,brackets[count]); } else if(brackets[count] == ']' || brackets[count] == ')') { //printf("%c\n", brackets); if( brackets[count] == ']' && (st->data[st->top] == '[') || brackets[count] == ')' && (st->data[st->top] == '(')) { Pop(st,&e); } else { printf("匹配失败\n"); return 0; } } count++; } //fflush(stdin); if(st->top == -1) printf("匹配成功\n"); else { printf("匹配失败\n"); }}
0 0
- 通过栈实现括号匹配
- 括号匹配代码实现--通过栈实现
- 栈实现括号匹配
- 栈实现括号匹配
- 栈实现括号匹配
- 栈实现括号匹配
- 括号匹配---栈实现
- 栈实现括号匹配
- 栈实现括号匹配
- 括号匹配,栈实现
- 栈实现括号匹配
- C/C++数据结构通过顺序栈实现括号()匹配算法
- 链栈实现括号匹配
- 括号匹配(栈实现)
- 用栈实现括号匹配
- 括号匹配问题--栈实现
- 栈的实现-括号匹配
- java栈实现括号匹配
- hihocoder 1037 数字三角形
- ValueError: could not convert string to float的处理方式
- ZTree节点单击展开
- MongoDB入门(3)--MongoDB的索引
- java-抽象类
- 通过栈实现括号匹配
- Node 192.168.206.130:7001 is not empty.Either the node already knows....异常
- 服务器隐藏Nginx的版本号
- AcitvityMQ的使用及详解
- Unity 自定义字体 新功能 一
- skyline二次开发示例代码
- 继承、多态
- Wine ---能够在多种 POSIX-compliant 系统上运行 Windows 应用的兼容层
- httpclient+asynctask下载图片并保存在本地