这是以前做的科学计算的栈以及功能函数,支持小数、多位数、加减乘除、括号运算,会自动判断表达式正误,希望对你有所帮助,当然也包括了括号匹配功能.其实括号匹配功能关键就在于左右大括号小括号的位置以及数量判断.根据实例分析一下很快就能写好算法.
//在In(c)里判断括号是否匹配
//栈及其功能声明部分
//SqStack_theta 为运算符栈
//SqStack_value 为数据栈
//_theta 为运算符栈功能函数标识
//_value 为数据栈功能函数标识
#define STACK_INIT_SIZE 100
#define STACKINCERMENT 5
#define ERROR 0
#define OK 1
#define OVERFLOW -2
#include"stdio.h"
#include"malloc.h"
#include"stdlib.h"
typedef char SElemTypeOPTR;
typedef double SElemTypeOPND;
typedef int Status;
typedef struct
{
x09SElemTypeOPTR *base;
x09SElemTypeOPTR *top;
x09int stacksize;
}SqStack_theta;
Status InitStack_theta(SqStack_theta &s)
{
x09s.base=(SElemTypeOPTR*)malloc(STACK_INIT_SIZE*sizeof(SElemTypeOPTR));
x09if(!s.base)exit(OVERFLOW);
x09s.top=s.base;
x09s.stacksize=STACK_INIT_SIZE;
x09return OK;
}
Status Push_theta(SqStack_theta &s,SElemTypeOPTR e)
{
x09if(s.top-s.base>=s.stacksize)
x09{
x09x09s.base=(SElemTypeOPTR*)realloc(s.base,(s.stacksize+STACKINCERMENT)*sizeof(SElemTypeOPTR));
x09x09if(!s.base)exit(OVERFLOW);
x09x09s.top=s.base+s.stacksize;
x09x09s.stacksize+=STACKINCERMENT;
x09};
x09*s.top++=e;
x09return OK;
}
Status Pop_theta(SqStack_theta &s,SElemTypeOPTR &e)
{
x09if(s.top==s.base) return OVERFLOW;
x09e=*--s.top;
x09return OK;
}
Status SEmpty_theta(SqStack_theta &s)
{
x09if(s.base==s.top)return OK;
x09else return ERROR;
}
Status GetTop_theta(SqStack_theta &s)
{
x09if(s.top==s.base) return OVERFLOW;
x09return *(s.top-1);
}
//
// OPND stack
//
typedef struct
{
x09SElemTypeOPND *base;
x09SElemTypeOPND *top;
x09int stacksize;
}SqStack_value;
Status InitStack_value(SqStack_value &s)
{
x09s.base=(SElemTypeOPND*)malloc(STACK_INIT_SIZE*sizeof(SElemTypeOPND));
x09if(!s.base)exit(OVERFLOW);
x09s.top=s.base;
x09s.stacksize=STACK_INIT_SIZE;
x09return OK;
}
Status Push_value(SqStack_value &s,SElemTypeOPND e)
{
x09if(s.top-s.base>=s.stacksize)
x09{
x09x09s.base=(SElemTypeOPND*)realloc(s.base,(s.stacksize+STACKINCERMENT)*sizeof(SElemTypeOPND));
x09x09if(!s.base)exit(OVERFLOW);
x09x09s.top=s.base+s.stacksize;
x09x09s.stacksize+=STACKINCERMENT;
x09};
x09*s.top++=e;
x09return OK;
}
Status Pop_value(SqStack_value &s,SElemTypeOPND &e)
{
x09if(s.top==s.base) return OVERFLOW;
x09e=*--s.top;
x09return OK;
}
SElemTypeOPND GetTop_value(SqStack_value &s)
{
x09if(s.top==s.base) return OVERFLOW;
x09return *(s.top-1);
}
//判断优先级 返回int型
//1 >
//0 =
//-1