Starting off, I just want to point out that the use of classes is for data hiding. Making your top
, size
, and other data members of public
scope completely defeats the purpose.
Secondly, the nomenclature of classes should start with an uppercase alphabet.
The first error is with your stack::Push(char)
method. Note the difference between return astack[--top]
and return astack[top--]
. The former decreases the value of top
by 1, and then returns the value, whereas, the latter returns the value of astack[top]
and then decrements top
.
This is very crucial as what you really want is to return the value popped, and not the value at the top of the stack after popping.
char stack::Pop() {
if (isEmpty()) {
cout << "The Array is already empty" << endl;
}
else {
// Note the change here.
return astack[top--];
}
}
Furthermore, since stack::print(stack *)
is a method of the class, every instance has its own copy for this member function. There is no need to explicitly pass an instance of stack
to it. You can achieve this by the following piece of code:
void stack::print() {
for (int i = 0; i <= top; ++i) {
cout << astack[i];
}
cout << "
";
}
Coming over to your precedence(char)
function, you need to break out of a switch condition when your goal is achieved.
int precedence(char element) {
switch (element) {
case '+': return 1;
case '-': return 1;
case '*': return 2;
case '/': return 2;
case '$': return 3;
default: return -1;
}
}
Moving onto your algorithm of converting infix to postfix, you have to keep popping all same or higher priority operators from the stack, and then push your scanned operator.
if (IsOperand(element)) {
post += element;
}
else if (IsOperator(element)) {
if (precedence(element) > precedence(postfix->Peek())) {
postfix->Push(element);
}
else {
while (precedence(element) <= precedence(postfix->Peek())) {
post += postfix->Pop();
}
postfix->Push(element);
}
}
I would suggest a few more changes such as adding to check for parantheses, but that seems to be out of the scope of this question. Good luck!
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…