注:本程序由Visual Studio 2015编写,与VC++6.0稍有区别,复制到VC++6.0注释掉“#include “stdafx.h””即可运行,复制到VS可直接运行。
#include “stdafx.h”
#include <stdio.h>
#include
#include <string.h>
using namespace std;
#define OK 1
#define ERROR 0
#define OVERFLOW -1
#define UNDERFLOW -2
#define STACK_INIT_SIZE 80
#define STACKINCREMENT 10
typedef int status;
#define ElemType char
typedef struct {
ElemType *base;
ElemType *top;
int stacksize;
}SqStack;
SqStack S;
status InitStack(SqStack &S) //初始化栈
{
S.base = (ElemType*)malloc(STACK_INIT_SIZE * sizeof(ElemType));
if (!S.base)exit(OVERFLOW);
S.top = S.base;
S.stacksize = STACK_INIT_SIZE;
return OK;
}
status Push(SqStack &S, ElemType e) {//入栈
if (S.top-S.base == S.stacksize) {
S.base = (ElemType*)realloc(S.base, (S.stacksize + STACKINCREMENT) * sizeof(ElemType));
if (!S.base)exit(OVERFLOW);
S.top = S.base + S.stacksize;
S.stacksize += STACKINCREMENT;
}
*S.top++ = e;
return OK;
}
status Pop(SqStack &S, ElemType &e) {//出栈
if (S.top == S.base)exit(UNDERFLOW);
e = *(S.top=S.top-1);
return OK;
}
status StackEmpty(SqStack S) {//是否为空栈
return S.base == S.top;
}
status match(char exp[50]) {//括号是否匹配
InitStack(S);
ElemType e;
for (int i = 0; i < strlen(exp); i++) {
switch (exp[i]) {
case '(':
case '[':
Push(S, exp[i]);
break;
case ')':
if (!StackEmpty(S))
{
Pop(S, e);
if (e == '(')
break;
else
return ERROR;
}
else
return ERROR;
case ']':
if (!StackEmpty(S))
{
Pop(S, e);
if (e == '[')
break;
else
return ERROR;
}
else
return ERROR;
}
}
if (StackEmpty(S))
return OK;
return ERROR;
}
int main() {
char exp[50];
cout << "\t\t\t\t*\t\t\t\t\t*";
cout << endl << "\t\t\t\t*\t计科1512-02210151232-杨少通\t*" << endl;
cout << "\t\t\t\t*****************************************" << endl << endl;
cout << "**************表达式括号是否匹配**************" << endl << endl;
cout << " 请输入表达式:";
cin >> exp;
if (match(exp))
cout << " 表达式括号匹配!" << endl << endl;
else
cout << " 表达式括号不匹配!" << endl << endl;
return 0;
}
本人初学数据结构,代码存在诸多问题,请各位看客多多指正。
如有转载请注明来源: www.dreamload.cn/blog/?p=238&preview=true (洋葱先生)
3665

被折叠的 条评论
为什么被折叠?



