啥也不多说直接上代码
#include <stdio.h>
typedef char ElemType;//将 ElemType声明成int类型
#define MaxSize 50 //定义栈中元素最大个数
typedef struct{//结构体
ElemType data[MaxSize];//存放栈中元素
int top; //栈顶指针
}SqStack;
//初始化栈
void InitStack(SqStack &S){
S.top=-1;
}
// 判断栈空
bool SatckEmpty(SqStack &S){
if(S.top==-1)
return true;//栈空
else
return false;//不空
}
//入栈
bool Push(SqStack &S,ElemType x){
if(S.top==MaxSize-1)//栈满报错
return false;
/**S.top=S.top+1;先指针加一
S.data[S.top]=x;再给指针指向的元素赋值**/
S.data[++S.top]=x;
return true;
}
//出栈
bool Pop(SqStack &S,ElemType &x){
if(S.top==-1)//栈空报错
return false;
x=S.data[S.top];//先取出栈顶元素
S.top=S.top-1;//栈顶指针减一
return true;
}
bool breaketCheck(char str[],int length){
SqStack S;
InitStack(S);//初始化一个栈
for(int i=0;i<=length;i++){
if(str[i]=='(' || str[i]=='{' || str[i]=='['){
Push(S,str[i]);//扫描到左括号都入栈
}else{
char topElem;
Pop(S,topElem);//取出栈顶元素和右括号匹配
if(str[i]==')' && topElem!='(')
return false;
if(str[i]=='}' && topElem!='{')
return false;
if(str[i]==']' && topElem!='[')
return false;
}
}
return SatckEmpty(S);//若最后的栈是空的则匹配成功
}
int main(){
char a[10];
int length=10;
printf("请输入5对括号\n");
for(int i=0;i<=10;i++)
{
scanf("%c",&a[i]);
}
if(breaketCheck(a,length)){
printf("括号匹配成功\n");
}else{
printf("括号匹配失败\n");
}
for(int i=0;i<=10;i++)
{
printf("%c\n",a[i]);
}
}
运行结果
请输入5对括号
[]{([])[]}
括号匹配成功
[
]
{
(
[
]
)
[
]
}