The question is to convert a postfix expression to an infix expression using stacks and without stack library.
Im getting a statement after i run it and enter my postfix expression saying : "Process returned -1073740940 (0xC0000374) execution time : 5.538 s"
The second i enter my postfix expression, the computer freezes and takes up a few seconds and then gives the statement. It does not even return the infix expression.
I have absolutely no clue why. It also somestimes can take 30-40s just for this error to pop up.
Edit#1: Okay so as @churill said, the misplaced parenthesis was an issue. i corrected that. now im getting this error immediately: "terminate called after throwing an instance of 'std::bad_alloc' what(): std::bad_alloc"
My code: (Edited once)
#include <iostream>
#include <ctype.h>
const int MAX = 20;
using namespace std;
class Stack {
private:
int top = -1;
string arr[MAX];
public:
bool isEmpty(){
if (top == -1){
return true;
}
else{
return false;
}
}
bool isFull(){
if(top == MAX-1){
return true;
}
else{
return false;
}
}
void push(string c){
if(isFull()){ //Edited line
cout<<"Stack Overflow"<<endl;
}
else{
top++;
arr[top] = c;
}
}
string pop(){
string val = arr[top];
arr[top] = '0';
top--;
return val;
}
string topele(){
string topelement = arr[top];
return topelement;
}
string display(){
int i;
for(i=top;i>=0;i--){
cout<<arr[i]<<endl;
}
}
bool isOperand(char c){
if(c >= 'a' && c <= 'z'){
return true;
}
else{
return false;
}
}
string posfixtoinfix(string postfix){
Stack s;
int i;
int len = postfix.size();
for(i=0;i<=len;i++){
if(s.isOperand(postfix[i])){ //Edited line
string op(1, postfix[i]);
s.push(op);
}
else{
string op1 = s.topele();
s.pop();
string op2 = s.topele();
s.pop();
string res = ("("+ (op2 + postfix[i] + op1) + ")");
s.push(res);
}
}
return s.topele();
}
};
int main(){
Stack s1;
string postfix, infix;
cout<<"Enter postfix expression: "<<endl;
cin>>postfix;
infix = s1.posfixtoinfix(postfix);
cout<<"The infix expression is: "<<infix<<endl;
return 0;
}