//环境:vs2010
//SeqStack.h
const int Maxsize=100;
template <class T>
class SeqStack
{
public:
SeqStack();//空栈的建立
~SeqStack(){}//
bool Empty();//空栈判断
bool Full();//满栈判断
int Length();//返回栈长度
void Push(T x);//元素x进栈
T Pop();//弹栈
T Gettop();//返回栈顶元素
private:
T data[Maxsize];
int top;//栈顶指针,即栈顶元素在数组中的下标
};
template <class T>
SeqStack<T>::SeqStack()//空栈的建立
{
top=-1;
}
template <class T>
bool SeqStack<T>::Empty()//空栈判断
{
if(top==-1)return true;
else return false;
}
template <class T>
bool SeqStack<T>::Full()//满栈判断
{
if(top==Maxsize-1)return true;
else return false;
}
template <class T>
int SeqStack<T>::Length()//返回栈长度
{
return top+1;
}
template <class T>
void SeqStack<T>::Push(T x)//元素x进栈
{
if(Full())throw "满栈";
top++;
data[top]=x;
}
template <class T>
T SeqStack<T>::Pop()//弹栈
{
if(Empty())throw "空";
T x=data[top];
top--;
return x;
}
template <class T>
T SeqStack<T>::Gettop()//返回栈顶元素
{
if(Empty())throw "空栈";
return data[top];
}
//BracketsCheck.cpp
#include "SeqStack.h"
#include <iostream>
using namespace std;
bool BracketsCheck(char str[]);
void main()
{
char ch[50];
cin>>ch;
cout<<(BracketsCheck(ch)?"匹配":"不匹配")<<endl;
}
bool BracketsCheck(char str[])
{
SeqStack<char> st;
int i=0;
char c;
while((c=str[i])!='\0')
{
switch(c)
{
case '(':
case '[':
case '{':
st.Push(c);break;
case ')':
if(st.Gettop()=='(')
st.Pop();
else
return false;
break;
case ']':
if(st.Gettop()=='[')
st.Pop();
else
return false;
break;
case '}':
if(st.Gettop()=='{')
st.Pop();
else
return false;
}
i++;
}
if(st.Empty())
return true;
else
return false;
}