判断表达式中的括号 ‘(’ 、 ')' 是否配对出现
#include <stack>
#include <iostream>
using namespace std;
template<class elemType>
class seqStack
{
private:
elemType*array;
int Top;
int maxSize;
void doubleSpace();
public:
seqStack(int initSize=100);
int isEmpty()
{
return (Top==-1);
};
int isFull()
{
return(Top==maxSize-1);
}
elemType top();
void push(const elemType&e);
void pop();
void sort();
~seqStack()
{
delete[]array;
};
};
template<class elemType>//初始化顺序栈
seqStack<elemType>::seqStack(int initSize)
{
array=new elemType[initSize];
if(!array) throw "illegalSize()";
Top=-1;
maxSize=initSize;
}
template<class elemType>
void seqStack<elemType>::doubleSpace()
{
elemType*tmp;
int i;
tmp=new elemType[maxSize*2];
if(!tmp) throw "illegalSize()";
for(i=0; i<=Top; i++) tmp[i]=array[i];//逐个复制节点
delete[]array;
array=tmp;
maxSize=2*maxSize;
}
template<class elemType>
elemType seqStack<elemType>::top()//返回栈顶元素的值
{
if(isEmpty()) throw "outOfBound()";
return array[Top];
}
template<class elemType>
void seqStack<elemType>::push(const elemType&e)//将元素e压入栈顶,使其成为新的栈顶元素
{
if(isFull()) doubleSpace();
array[++Top]=e;
}
template <class elemType>
void seqStack<elemType>::pop()//将栈顶元素弹栈
{
if (Top==-1) throw "outOfBound()";
Top--;
}
int main()
{
char str[20];
seqStack<char>s;
char ch;
cout<<"Input the string:";
cin.getline(str,20,'\n');
cout<<"str:"<<str<<endl;
int i=0;
ch=str[i++];
while(ch!='\0')
{
switch(ch)
{
case'(':
s.push(ch);
break;
case')':
if(s.isEmpty())//
{
cout<<"An opening bracket";
return 1;
}
else
s.pop();
break;
}
ch=str[i++];
}
if(!s.isEmpty())
cout<<"A closing bracket ')' is expected!"<<endl;
return 0;
}