#include <cstdio>
#include <stdlib.h>
#define Stack_size 100
typedef char ElemType;
typedef struct Node
{
ElemType elem[Stack_size];
int top;
} Seqstack;
void Initstack (Seqstack *s)
{
s->top=-1;
}
int Push(Seqstack *s, ElemType x) //将元素x入栈
{
if(s->top==Stack_size-1) return false;
s->top++;
s->elem[s->top]=x;
return true;
}
#include <stdlib.h>
#define Stack_size 100
typedef char ElemType;
typedef struct Node
{
ElemType elem[Stack_size];
int top;
} Seqstack;
void Initstack (Seqstack *s)
{
s->top=-1;
}
int Push(Seqstack *s, ElemType x) //将元素x入栈
{
if(s->top==Stack_size-1) return false;
s->top++;
s->elem[s->top]=x;
return true;
}
int Pop(Seqstack *s, ElemType *x) //将栈顶元素出栈 通过x带出
{
if(s->top==-1) return false;
else{
*x=s->elem[s->top];
s->top--;
return true;
}
}
{
if(s->top==-1) return false;
else{
*x=s->elem[s->top];
s->top--;
return true;
}
}
int Gettop(Seqstack *s, ElemType *x) //读出栈顶元素 通过x带出
{
if(s->top==-1) return false;
else{
*x=s->elem[s->top];
return true;
}
}
{
if(s->top==-1) return false;
else{
*x=s->elem[s->top];
return true;
}
}
int Isempty(Seqstack *s) //判断栈是否为空 空的话返回1 非空返回0
{
if(s->top==-1) return true;
else return false;
}
{
if(s->top==-1) return true;
else return false;
}
int IsFull(Seqstack *s ) //判断栈是否满了 满的话返回1 不满返回0
{
if(s->top==Stack_size-1) return true;
else return false;
}
{
if(s->top==Stack_size-1) return true;
else return false;
}
int Match(char a,char b)
{
if(a=='(' && b==')') return 1;
if(a=='{' && b=='}') return 1;
if(a=='[' && b==']') return 1;
return 0;
}
void BracketMatch(char *str )
{
Seqstack s;char ch;
Initstack(&s);
for(int i=0;str[i]!='\0';i++)
{
switch(str[i])
{
case '(':
case '[':
case '{':
Push(&s,str[i]);
break;
case ')':
case ']':
case '}':
if(Isempty(& s)) {
printf("匹配不成功\n");
return ;
}
else{
Gettop(&s,&ch);
if(Match(ch,str[i])) Pop(&s,&ch);
else {
printf("匹配不成功\n");
return;
}
}
}
}
if(Isempty(&s)) printf("匹配成功\n");
else printf("左括号多余\n");
}
int main()
{
char str[20];
printf("请输入要匹配的括号\n");
scanf("%s",&str);
BracketMatch(str);
return 0;
}
{
if(a=='(' && b==')') return 1;
if(a=='{' && b=='}') return 1;
if(a=='[' && b==']') return 1;
return 0;
}
void BracketMatch(char *str )
{
Seqstack s;char ch;
Initstack(&s);
for(int i=0;str[i]!='\0';i++)
{
switch(str[i])
{
case '(':
case '[':
case '{':
Push(&s,str[i]);
break;
case ')':
case ']':
case '}':
if(Isempty(& s)) {
printf("匹配不成功\n");
return ;
}
else{
Gettop(&s,&ch);
if(Match(ch,str[i])) Pop(&s,&ch);
else {
printf("匹配不成功\n");
return;
}
}
}
}
if(Isempty(&s)) printf("匹配成功\n");
else printf("左括号多余\n");
}
int main()
{
char str[20];
printf("请输入要匹配的括号\n");
scanf("%s",&str);
BracketMatch(str);
return 0;
}