Chinaunix首页 | 论坛 | 博客
  • 博客访问: 213084
  • 博文数量: 35
  • 博客积分: 1480
  • 博客等级: 上尉
  • 技术积分: 390
  • 用 户 组: 普通用户
  • 注册时间: 2007-11-14 14:27
文章分类

全部博文(35)

文章存档

2008年(35)

我的朋友

分类: C/C++

2008-03-19 08:58:23

/*一唯数组A中保存由字母(变量),运算符(+,-,*,/)和圆括号组成的算术表达式,
圆括号允许嵌套,请编写函数,检查表达式中的括号是否配对*/
#include "iostream"
using namespace std;
enum ResultCode{Underflow,Overflow};
template
class Stack
{
public:
 virtual void Push(const T &x)=0;
 virtual void Pop()=0;
 virtual T Top() const=0;
 virtual bool IsEmpty() const=0;
 virtual bool IsFull() const=0; 
};
template
class SeqStack:public Stack
{
public:
 SeqStack(int mSize);
 ~SeqStack(){delete[] s;}
 bool IsEmpty() const {return (top==-1);}
 bool IsFull() const {return (top==maxSize-1);}
 void Push(const T &x);
 void Pop();
 T Top() const;
private:
 void Output(ostream & out)const;
 T *s;
 int maxSize;
 int top;
 friend ostream &operator<<(ostream & out,SeqStack & s);
};
template
SeqStack::SeqStack(int mSize)
{
 maxSize=mSize;
 s=new T[maxSize];
 top=-1;
}
template
void SeqStack::Pop()
{
 if(IsEmpty()) throw Underflow;
  top--;
}
template
void SeqStack::Push(const T &x)
{
 if(IsFull()) throw Overflow;
 s[++top]=x;
}
template
T SeqStack::Top() const
{
 if(IsEmpty()) throw Underflow;
 return s[top];
}
template
void SeqStack::Output(ostream& out) const
{
out<<"the stack contains:"<for(int i=top;i>-1;i--)
out<out<}
template
ostream& operator<<(ostream& out,SeqStack& s)
{
 s.Output(out);
 return out;
}
void find()
{
char str[20];
char c;
int i=0;
SeqStack seq(100);
while((c=getchar())!='\n')
{
str[i]=c;
i++;
}
try{
for(int j=0;j{
if(str[j]=='(')
seq.Push(str[j]);
else if(str[j]==')')
{
if(seq.IsEmpty()) throw Underflow;
else
seq.Pop();
}
}
cout<<"the expression is ";
}
catch(ResultCode err)
{
 switch(err)
 case Underflow:cout<<"wrong"<}
if(!seq.IsEmpty())
cout<<"wrong"<else
cout<<"right"<}
int main()
{
 find();
 return 0;
}
阅读(1364) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~