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

 

 

#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;     
}     

相关文章:

  • 2021-12-19
  • 2021-09-28
  • 2022-12-23
  • 2021-06-20
  • 2022-12-23
  • 2021-08-10
  • 2021-09-01
猜你喜欢
  • 2021-06-04
  • 2022-12-23
  • 2021-11-14
  • 2022-12-23
  • 2021-05-03
  • 2021-06-21
  • 2022-12-23
相关资源
相似解决方案