编写程序,检验括号配对的匹配是否正确。假设表达式中只有两种括号,‘(’和‘]’,嵌套顺序任意,即([})或者[()]为正确的表达式。该程序也运用了栈的思想。若是左括号则入栈,若是右括号则看是否和当前栈顶元素是否匹配。若是则Pop(),不是则当前表达式括号不匹配。代码详见下。主要是看Bracket()函数。其他则是栈的基本操作。
#include <stdio.h>
#include <malloc.h>
#define STACK_SIZE 200
#define EleType char
//栈的节点声明
typedef struct Stack{
EleType top;
EleType array[STACK_SIZE];
}Stack,*pStack;
//初始化一个空栈
int Init_Stack(pStack S){
S->top = 0;//top为0表示空栈
return 1;
}
//测试是否为空栈
int IsEmpty(pStack S){
if(S->top==0)return 1;
else return 0;
}
//元素e入栈
int Push(pStack S,EleType e){
S->top++;
S->array[S->top] = e;
return S->top;
}
//出栈,并返回该元素值
EleType Pop(pStack S){
S->top--;
return S->array[S->top+1];
}
//括号匹配函数
int Bracket(pStack S,char a[],int length){
int i=0;
for(;i<length;i++){
if(a[i]==']'||a[i]==')'){
switch(a[i]){
case ')': if('('!=Pop(S)){Error();};break;
case ']': if('['!=Pop(S)){Error();};break;
default:printf("Error!");break;
}
}else{
if((a[i]=='(')||(a[i]=='[')){
Push(S,a[i]);
}
else{Error();}
}
}
if(IsEmpty(S)){
printf("ok!");
return 1;
}
else{
printf("failed");
return 0;}
}
int Error(){
printf("Error");getch();exit(-1);
}
void main(){
pStack S;
char a[]="[([][])]";
S = (pStack)malloc(sizeof(Stack));
Init_Stack(S);
Bracket(S,a,8);
getch();
}
加载中,请稍候......