您的位置:首页 > 其它

利用栈写一个程序, 检验文本中的圆括号、方括号、花括号是否正确嵌套.

2014-06-02 11:11 246 查看
正确的嵌套是指: [()] 是合法的, 但 [(]) 就是错误的.

算法:

做一个空栈, 读入字符直至文件尾.
如果字符是一个开放符号, 则将其压入栈中.
如果字符是一个封闭符号, 那么若栈为空, 则报错; 若栈不为空, 则将栈元素弹出.
如果弹出的符号不是对应的开放符号, 则报错.
在文件尾, 如果栈非空则报错.

代码实现

#include<iostream>
#include<fstream>
#include<stack>
#include<cstdlib>
using namespace std;
bool match(string &file)
{
ifstream File;
stack<char>CC;
File.open(file.c_str());
if(!File)
{
cerr<<"Error!!\nUnable to find the file!"<<endl;
exit(1);
}
char CH;
int symb;
while(File.get(CH))
{
switch(CH)
{
case'(':symb=1;break;
case'[':symb=2;break;
case'{':symb=3;break;
case'<':symb=4;break;
case')':symb=8;break;
case']':symb=7;break;
case'}':symb=6;break;
case'>':symb=5;break;
default:symb=10;
}
if(symb>=1&&symb<=8)
{
if(symb<=4)
{
if(CC.size()!=0&&CC.top()<symb) return false;
else CC.push(symb);
}
else
{
if(CC.size()==0) return false;
else if(symb+CC.top()==9) CC.pop();
else   return false;
}
}
}
if(CC.size()>0)  return false;
return true;
}
int main()
{
string filename;
cout<<"Please enter your file name:"<<endl;
getline(cin,filename);
if(match(filename))
cout<<"****Congradulations!!****\nYour file's symbols are matched."<<endl;
else
cout<<"****Sorry man****\nPlease correct your file"<<endl;
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐