#include <cstdio>
#include <iostream>
using namespace std;
#define MAXSIZE 20
typedef struct {
char *base;
char *top;
int stacksize;
}SqStack;
void InitStack(SqStack &S)
{
S.base = (char *)malloc( MAXSIZE * sizeof(char) );
if(S.base == NULL) exit(-2);
S.top = S.base;
S.stacksize = MAXSIZE;
}
void GetTop(SqStack S, char &e)
{
if(S.top == S.base)
return;
e = *(S.top - 1);
}
void Push(SqStack &S, char e) // 不考虑栈满
{
*S.top++ = e;
}
void Pop(SqStack &S, char &e)
{
if(S.top == S.base)
return;
S.top--;
e = *S.top;
}
bool Match(char c, SqStack &my_stack, bool &tag)
{
char e;
Pop(my_stack, e);
if ( c != e ) {
tag = false;
free(my_stack.base);
return false; // match fail
}
return true; // match success
}
void Correct(char *expr, bool &tag)
{
tag = true;
SqStack my_stack;
InitStack (my_stack);
for( int i = 0; expr[i] != '\0'; i++ ) {
char c = expr[i];
switch(c) {
case '{' : case '[' : case '(' :
Push (my_stack, c); break;
case '}' :
if( Match('{', my_stack, tag) == false ) // match fail
return;
break;
case ']' :
if( Match('[', my_stack, tag) == false ) // match fail
return;
break;
case ')' :
if( Match('(', my_stack, tag) == false ) // match fail
return;
break;
default :
break; // 其它字符
}
}
if(my_stack.top != my_stack.base) // e.g.: "[r"
tag = false;
free(my_stack.base);
}
int main(void)
{
// freopen("cin.txt", "r", stdin);
char my_expr[MAXSIZE];
while(cin >> my_expr) {
bool tag = true;
Correct( my_expr, tag);
tag ? printf("匹配成功\n") : printf("匹配失败\n");
}
return 0;
}
(另见 http://blog.csdn.net/justme0/article/details/7424798)
分享到:
相关推荐
是括号匹配栈的实现,利用栈的后进先出的原理,希望对大家会有所帮助
C语言实现栈实现括号匹配,很好用,有需要的来下载。
用栈实现括号匹配的检测,链式栈实现 ()[]的检测可以实现
数据结构中利用栈实现括号匹配 本资源有两个文件 main.cpp Stack.h
利用栈实现括号匹配的检验,存储括号字符的数组通过malloc实现动态分配长度,匹配函数的第一个参数为指向字符的指针(即为存储括号字符的数组的首地址)和一个整数(即为括号字符的总数,为括号个数的2倍),将左...
利用栈实现括号匹配的算法代码,数据结构算法
括号匹配使用栈实现括号匹配.cpp
使用顺序栈实现括号匹配
用顺序栈的方法实现括号匹配的检查,例如输入( enter【enter{enter}enter】enter)enter,程序就会输出Match(匹配),注enter是回车。
顺序栈实现括号配对
数据结构作业采用栈进行括号匹配并用MFC实现,程序加源码
用c++ 语言实现的括号匹配程序,利用栈实现
自制的用标准栈实现括号匹配,两种语言界面。可简单实现{}、[]、()括号的匹配。 作者:sharlon123 QQ:370854700
Stack to achieve a brace matching algorithms, data structures, the matching parenthesis
c++使用堆栈实现括号匹配问题
用栈实现括号匹配。而且使得操作尽可能简单,所以就之用了基本的进,出栈的操作。
本程序包含 栈体:用来保存数据项的内存空间; 栈顶指示器:用来指示栈顶数据项; 栈操作: 压栈操作(push):把数据项从栈顶压入栈内,移动栈顶指示...判断一个数学表达式中的括号(包括圆括号和方括号)是否配对。
用栈实现括号匹配 对表达式进行扫描 凡遇到(就将栈顶元素(出栈 表达式被扫描完毕 栈应为空
数据结构(严蔚敏版)P49的括号匹配的代码实现
数据结构栈和队列的基本应用——括号匹配问题的设计与实现,使用C++实现,包括如何创建栈,进行括号匹配等,思路清晰。