在编写程序的过程中,我们经常需要对一串括号是否匹配进行判断。如何判断呢?我们可以借助栈来进行判断。基本思路是:遍历字符串,当发现有右括号而此时的栈顶元素又恰好是与之匹配的左括号时,则栈顶元素出栈;其余情况全部入栈,代码如下:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define OK 1
#define ERROR 0
#define TRUE 1
#define FALSE 0
#define MAXSIZE 30
typedef int status;
typedef char elemtype;
typedef struct sqstack{
elemtype data[MAXSIZE];
int top;
}stack;
status traversestack(sqstack *s){
int i=0;
for(i=s->top;i>=0;i--){
printf("%d ",s->data[i]);
}
printf("\n");
}
status initstack(sqstack *s){
s->top=-1;//置空栈
}
//将元素压入栈
status push(sqstack *s,elemtype data)
{
if(s->top==MAXSIZE-1){
return ERROR;//判断栈是否已满
}
else{
s->top++;
s->data[s->top]=data;
}
return OK;
}
status emptystack(sqstack *s){
if(s->top==-1){
return TRUE;
}
else{
return FALSE;
}
}
//出栈并返回元素值
status pop(sqstack *s){
if(s->top==-1){
return ERROR;
}
else{
elemtype e;
e=s->data[s->top];
s->top--;
return e;
}
}
//返回栈长
status stacklength (sqstack *s){
return s->top+1;
}
//出栈
status pop(sqstack *s,elemtype data){
if(s->top==-1){
printf("空栈\n");
return ERROR;
}
else{
data=s->data[s->top];
s->top--;
printf("出栈元素为%d\n",data);
}
}
status main(void){
elemtype ch[MAXSIZE];
stack S;
initstack(&S);
scanf("%s",ch);
int i=0;
for(i=0;i<strlen(ch);i++){
if(ch[i]==')'&&S.data[S.top]=='('||ch[i]==']'&&S.data[S.top]=='['||ch[i]=='}'&&S.data[S.top]=='{')/*出栈条件*/
pop(&S);
else
push(&S,ch[i]);
}
if(S.top==-1){
printf("YES\n");
}
else
printf("NO\n");
}