admin 管理员组

文章数量: 1184232


2024年4月18日发(作者:没有filter函数怎么办)

Stack-匹配多种括号

假设一个算法表达式中可以包含三种括号:圆括号“(”和“)”,方括号“[”和“]”,

花括号“{”和“}”,且这三种括号可按任意的次序嵌套使用。编写判别给定表达式中所含

括号是否正确匹对出现的算法

#include #include

#define STACKSIZE 100

#define SIZEINCREAMENT 20

typedef struct { //栈

char *base;

char *top;

int stackSize;

} SqStack;

void initStack(SqStack &S) { //初始化一个栈

= = (char *)malloc(sizeof(char) * STACKSIZE);

ize = STACKSIZE;

}

void pop(SqStack &S, char &e) { //出栈

if( == ) { e = NULL; return ; }

e = *--;

}

void push(SqStack &S, char e) { //入栈

if( - >= ize) {

= (char *)realloc(, (ize

sizeof(char));

= + ize;

ize += SIZEINCREAMENT;

}

* = e;

SIZEINCREAMENT) * +

++;

}

bool match(char c1, char c2) { //c1和c2是否匹配

if((c1 == '{' && c2 == '}') || (c1 == '[' && c2 == ']') || (c1 == '(' && c2 == ')'))

return true;

return false;

}

bool isBracketMatch() { //匹配括号

SqStack bracketStack;

char c, ch;

c = getchar();

initStack(bracketStack);

while(c != 'n') {

if(c == '{' || c == '[' || c == '(') {

push(bracketStack, c);

} else if(c == '}' || c == ']' || c == ')') {

if( == ) return false;

pop(bracketStack, ch);

if(!match(ch, c)) return false;

}

c = getchar();

}

if( == ) return true;

return false;

}

void main() {

printf("请输入括号:圆括号“(”和“)”,方括号“[”和“]”,花括号“{”和

n"); “}”

if(isBracketMatch()) printf("括号是匹配的!n");

else printf("括号是不匹配的!n");

}


本文标签: 括号 表达式 编写 使用