//中缀表达式转后缀表达式
/*特别注意 中缀表达式转为后缀表达式:当运算符优先级比栈顶运算符高时直接入运算栈,如果等于或低于栈顶运算符时将运算符栈的出栈 (转为前缀表达式时没有等于)
*/
#include <iostream>
#include <stack>
using namespace std;
int main()
{
string str;
stack<char> opr;
stack<char> open;
cout << "输入一个中缀表达式:"<< endl;
cin >> str;
cout << "原表达式为:" << str << endl;
auto i = str.begin();
while (i != str.end())
{
switch (*i)
{
case '(':
{
opr.push(*i); // 入栈
++i;
break;
}
case '+':
case '-':
{
if (opr.empty())
{
opr.push(*i);
++i;
break;
}
while (!opr.empty() && opr.top() != '(')
{
open.push( opr.top() ); // 当前运算符优先级低于操作符时 //把操作符栈内的入到数栈
opr.pop(); // 出栈
}
opr.push(*i);
++i;
break;
}
case '*':
case '/':
{
if (opr.empty())
{
opr.push(*i);
++i;
break;
}
if ( (opr.top() == '+' || opr.top() == '-') ||
opr.top() =='(' )
{ opr.push(*i);
++i;
break;
}
while (!opr.empty() &&
(opr.top() == '/' || opr.top() == '*') )
{
open.push(opr.top());
opr.pop();
}
opr.push(*i);
++i;
break;
}
/* case '/':
{
// while (!opr.empty() && opr.top() != '(')
opr.push(*i);
++i;
break;
}
*/
case ')':
{
while (opr.top() != '(')
{
open.push(opr.top());
opr.pop();
}
if (opr.top() == '(')
opr.pop();
++i;
break;
}
default :
{
open.push(*i);
++i;
break;
}
}
}
//opr弹出到open
while (!opr.empty())
{
open.push(opr.top());
opr.pop();
}
cout << "操作完毕:" << endl;
//显示栈:
while (!open.empty())
{
cout << open.top();
open.pop();
}
return 0;
}
//括号配对问题
#include <iostream>
#include <stack>
using namespace std;
int main()
{
string str;
cout << "请输入一串只有()[]的字符" << endl;
cin >> str;
cout << "str 中的元素是:" << str << endl;
stack<char>sta; // 注意是char类型的
auto i = str.begin();
while (i != str.end())
{
if (*i == '(' || *i == '[')
{
sta.push(*i);
i++;
}
else if ( *i == ')')
{
if (sta.empty() || sta.top() != '(')
{
cout << "no" << endl;
return 0;
}
else if(sta.top() == '(')
{
sta.pop();
++i;
}
}
else if (*i == ']')
{
if (sta.empty() || sta.top() != '[')
{
cout << "no" << endl;
return 0;
}
else if (sta.top() == '[')
{
sta.pop();
++i;
}
}
}
if (sta.empty())
cout << "yes" << endl;
else
cout << "no" << endl;
cout << "结束";
return 0;
}