📄 infixtopostfix.h
字号:
// InfixToPostfix.cpp : Defines the entry point for the console application.
#include "stdafx.h"
#include<iostream>
#include<string>
#include<stack>
#include<cctype>
#include<vector>
using namespace std;
int Priority(char optr)//设定运算符的优先级
{
switch (optr)
{
// case '(':
// return 0;
case '+':
case '-':
return 1;
case '*':
case '/':
return 2;
}
}
int InfixToPostfix()
{
stack<char> s;
vector<char> vecPostfix;
string operatorSymbol = "+-*/()";
enum state{OPERAND, OPERATOR};
state prospectiveElement = OPERAND;
char ch,topElement;
int operandNum = 0, operatorNum = 0;
int errorFlag = 0;
cout<<"Please enter an arithmetic expression and end it by #:" << endl;
while(cin.get(ch)&&ch!='#')
{
if(isdigit(ch)||isalpha(ch))
{
operandNum++;
if (prospectiveElement != OPERAND)
{
cout << "Invalid Input!" << endl; //lack of operator
errorFlag = 1;
}
vecPostfix.push_back(ch);
prospectiveElement = OPERATOR;
}
else
{
int index = operatorSymbol.find_first_of(ch);
if (index == -1)
{
cout << "Invalid Input!" << endl; //illegal type of operator (legal type:\"+-*/()\")
errorFlag = 1;
}
if (ch == '(')
s.push(ch);
else if (ch == ')')
{
if (prospectiveElement != OPERATOR)
{
cout << "Invalid Input!" << endl;//lack of operand
errorFlag = 1;
}
while (!s.empty() && s.top() != '(')
{
topElement = s.top();
s.pop();
vecPostfix.push_back(topElement);
}
if (s.empty())
{
cout << "Invalid Input" << endl;//lack of '('
errorFlag = 1;
}
else
s.pop();
}
else
{
operatorNum++;
if (prospectiveElement != OPERATOR)
{
cout << "Invalid Input!" << endl; //lack of operator
errorFlag = 1;
}
prospectiveElement = OPERAND;
if (s.empty())
s.push(ch);
else
{
topElement = s.top();
while ((!s.empty()) && (topElement != '(') && (Priority(topElement) >= Priority(ch)))
{
s.pop();
vecPostfix.push_back(topElement);
if (!s.empty())
topElement = s.top();
}
s.push(ch);
}
}
}
}
if (operandNum - operatorNum != 1)
{
cout << "Invalid Input!" << endl;//lack of operand
errorFlag = 1;
}
while (!s.empty())
{
topElement=s.top();
if (topElement == '(')
{
cout << "Invalid Input!" << endl; //lack of ')'
errorFlag = 1;
}
s.pop();
vecPostfix.push_back(topElement);
}
if (errorFlag == 1)
return 1;
for (int i = 0; i < vecPostfix.size(); i++)
{
if (i != vecPostfix.size() - 1)
cout << vecPostfix[i] << ", ";
else
cout << vecPostfix[i];
}
cout << endl;
system ("PAUSE");
return 0;
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -