(C语言)判断表达式中括号是否匹配-洋葱先生-杨少通
发布日期:2021-10-03 07:58:41 浏览次数:1 分类:技术文章

本文共 2015 字,大约阅读时间需要 6 分钟。

注:本程序由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 (洋葱先生)

转载地址:https://blog.csdn.net/Kindergarten_Sir/article/details/108587432 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:(C语言)十进制转换成R进制-洋葱先生-杨少通
下一篇:时间计时(JQ)-洋葱先生-杨少通

发表评论

最新留言

留言是一种美德,欢迎回访!
[***.207.175.100]2024年04月11日 20时57分02秒