基于栈的括号匹配
#include<iostream>
using namespace std;
#define MAXSIZE 100
typedef char Elemtype;
typedef struct
{
Elemtype elem[MAXSIZE];
int top;
}Seqstack;
void Initstack(Seqstack &s);
bool Isempty(Seqstack s);
bool Isfull(Seqstack s);
void Push(Seqstack &s, Elemtype e);
void Pop(Seqstack &s, Elemtype &e);
void Gettop(Seqstack s, Elemtype &e);
void BracketMatch(char *str);
int main()
{
char str[MAXSIZE];
cin >> str;
BracketMatch(str);
return 0;
}
void Initstack(Seqstack &s)
{
s.top = -1;
}
bool Isempty(Seqstack s)
{
if (s.top == -1)
{
return true;
}
else
{
return false;
}
}
bool Isfull(Seqstack s)
{
if (s.top == MAXSIZE - 1)
{
return true;
}
else
{
return false;
}
}
void Push(Seqstack &s, Elemtype e)
{
if (Isfull(s))
{
cout << "顺序栈已满!" << endl;
}
else
{
s.top++;
s.elem[s.top] = e;
}
}
void Pop(Seqstack &s, Elemtype &e)
{
if (Isempty(s))
{
cout << "顺序栈为空!" << endl;
}
else
{
e = s.elem[s.top];
s.top--;
}
}
void Gettop(Seqstack s, Elemtype &e)
{
if (Isempty(s))
{
cout << "顺序栈为空!" << endl;
}
else
{
e = s.elem[s.top];
}
}
void BracketMatch(char *str)
{
Seqstack s; char e;
Initstack(s);
for (int i = 0; str[i] != '\0'; i++)
{
switch (str[i])
{
case '(':
case '[':
case '{':
Push(s, str[i]);
break;
case ')':
{
if (Isempty(s))
{
cout << "右小括号多余!" << endl;
exit(1);
}
else
{
Pop(s, e);
if (e != '(')
{
cout << "小括号不匹配!" << endl;
exit(1);
}
}
break;
}
case ']':
{
if (Isempty(s))
{
cout << "右中括号多余!" << endl;
exit(1);
}
else
{
Pop(s, e);
if (e != '[')
{
cout << "中括号不匹配!" << endl;
exit(1);
}
}
break;
}
case '}':
{
if (Isempty(s))
{
cout << "右大括号多余!" << endl;
exit(1);
}
else
{
Pop(s, e);
if (e != '{')
{
cout << "大括号不匹配!" << endl;
exit(1);
}
}
break;
}
}
}
if (Isempty(s))
{
cout << "括号匹配!!!" << endl;
}
else
{
cout << "左括号多余!" << endl;
}
}