【原创】利用栈解决括号匹配问题

 

本例利用栈的先进后出,后进先出的原理解决了括号()[]{}<>匹配的问题

 

 

#include <iostream>
#include <stack>
 
using namespace std;
 
int main()
{
    char ch;
    stack<char> s;
    try
    {
        do
        {
             cin >>ch;
             if(ch=='(' ||ch=='[' ||ch=='{' ||ch=='<') s.push(ch);
             if(ch==')' || ch==']' || ch=='}' || ch=='>')
             {
                  if(s.empty()) throw ch;  
                  if(ch==char(s.top()+2) || ch==char(s.top()+1)) 
                      s.pop();      
             }
        }while(ch!='#');
        if(!s.empty()) 
             throw s.top(); 
        cout <<"括号匹配";
    }
     
    catch(char& c)
    {
          cout <<c <<"不匹配";       
    }
    cout <<endl;
    system("pause");
    return 0;     
}     
posted @ 2009-11-17 22:00  leukotrichia  阅读(468)  评论(0编辑  收藏  举报