インフィックスをposfixに変換しようとしていますが、優先順位が機能していません。助けてください!コードはC++で書かれています。私のコードは "ABCDEF + ** + *"を出力します。これを正しく理解していれば、 "ABCDEF **** ++"を出力するはずです。 *は+よりも優先されます。助けてくれてありがとう。ここに私のコードは次のとおりです。A*B+C*D*E+f is AB*CD*E*+F+
Postfixへのインフィックス - 優先順位が機能しない
の
#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;
}
へ
私のコードは、これを正しく理解していれば、ABCDEF *** ++を出力しなければならないとABCDEF + ** + *を出力します。 *は+よりも優先されます。 – hockey34
私はどちらかが正しいとは思わない。通常の演算子の優先順位を仮定すると、あなたのin-fixは '(a * b)+(c * d * e)+ f'を求めています。 + 'を修正してください。あなたが最初に修正したもの(あなたが印刷したもの)は 'a *(b +(c * d *(e + f)))'を表し、 'a + b +(c * d * e * f) 'となります。おそらく注目すべきは、私が思うところでのオペレータの順序は、あなたが期待しているものと一致しているということです。 – TripeHound