我正在尝试将中缀转换为posfix,但优先级不起作用。请帮忙!代码是用C ++编写的。我的代码打印出“ABCDEF + ** + *”,当我认为它应该打印出“ABCDEF **** ++”,如果我正确理解这一点。 *优先于+。感谢你们对我的帮助。这是我的代码:
#include <iostream>
#include <string>
using std::cout;
using std::cin;
using std::endl;
using std::string;
struct node{
char value;
struct node *link;
};
node *top;
class stack{
private:
int counter;
public:
node *pushInto(node*, char);
node *popOut(node*);
void traverseStack(node*);
int isStackEmpty();
stack()
{
top = nullptr;
counter = 0;
}
};
node *stack::pushInto(node *top, char a)
{
node *temp;
temp = new (struct node);
temp -> value = a;
temp -> link = top;
top = temp;
counter++;
return top;
}
node *stack::popOut(node *top)
{
node *temp;
char item;
if (top == nullptr)
{
cout << "Stack is empty";
}
else
{
temp = top;
item = temp -> value;
cout << item;
top = top -> link;
delete temp;
counter--;
}
return top;
}
void stack::traverseStack(node *top)
{
node *temp;
temp = top;
if (top == nullptr)
{
cout << "Stack is empty.";
}
else
{
while (temp != nullptr)
{
cout << temp -> value << endl;
temp = temp -> link;
}
}
}
int stack::isStackEmpty()
{
if (top == nullptr)
return 0;
return -1;
}
class infixToPostfix:public stack{
public:
bool isOperand(char);
bool isOperator(char);
int weightOfOperator(char);
char precedence(char, char);
void output(char[]);
};
bool infixToPostfix::isOperand(char a)
{
if (a >= 'A' && a <= 'Z')
return true;
return false;
}
bool infixToPostfix::isOperator(char a)
{
if (a == '*' || a == '/' || a == '+' || a == '-')
return true;
return false;
}
int infixToPostfix::weightOfOperator(char a)
{
int weight;
if (a == '*' || a == '/')
weight = 2;
else if (a == '+' || a == '-')
weight = 1;
else
weight = -1;
return weight;
}
char infixToPostfix::precedence(char a, char b)
{
if (weightOfOperator(a) > weightOfOperator(b))
{
return a;
return b;
}
return NULL;
}
void infixToPostfix::output(char a[])
{
const int length = 11;
// const int numberOperators = 5;
char output[length];
for (int i = 0; i < length; i++)
{
if (isOperand(a[i]))
{
output[i] = a[i];
}
else
{
top = pushInto(top, a[i]);
}
cout << output[i];
}
for (int i = 1; i < length; i+=2)
{
if (precedence(a[i], a[i + 1]))
{
top = popOut(top);
}
}
}
int main()
{
infixToPostfix result;
const int length = 11;
char infix1[length] = {'A', '*', 'B', '+', 'C', '*', 'D', '*', 'E', '+', 'F'}; //Initalize and declare first infix pattern
// char infix2[length] = {'A', '+', 'B', '*', 'C', '+', 'D', '+', 'E', '*', 'F'};
result.output(infix1);
cout << "\n";
// result.output(infix2);
return 0;
}
答案 0 :(得分:0)
A*B+C*D*E+f is AB*CD*E*+F+
您的优先功能似乎不正确
char infixToPostfix::precedence(char a, char b)
{
if (weightOfOperator(a) > weightOfOperator(b))
{
return a;
return b;// unreachable
}
return NULL // return type does not match
}
将其更改为
char infixToPostfix::precedence(char a, char b)
{
if (weightOfOperator(a) > weightOfOperator(b))
{
return a;
}
return b;
}