I am trying to create a program to convert an infix expression to a postfix expression using stack data structure in c++ using a structure Node. The related functions are there to push, pop values from the stack. The program compiles but after i enter a infix expression example 'a+b' in the output window, there is a runtime error. Here is the complete code..
#include <iostream>
#include<cstring>
using namespace std;
struct Node{
char data;
struct Node * next;
}*top=NULL;
void Push(char x)
{ struct Node* p=new Node;
if(p==NULL)
cout<<"\nStack Overflow";
else{
p->data=x;
p->next=top;
top=p;
}
}
char Pop(){
int x=-1;
struct Node * p;
if(top==NULL)
cout<<"\nStack is Empty";
else{
p=top;
x=p->data;
top = top->next;
delete p;
}
return x;
}
int isEmpty(){
return top?0:1;
}
int Pre(char ch){
if(top==NULL)
return 0;
else if(ch == '-' || ch == '+')
return 1;
else if(ch == '*' || ch == '/')
return 2;
else
return 3;
}
char * InToPost(char *infix){
char *postfix = new char[strlen(infix)+1];
int i=0,j=0;
while(infix[i]!='\0')
{
if(Pre(infix[i]>Pre(top->data)))
Push(infix[i++]);
else{
while(Pre(infix[i])<=Pre(top->data))
postfix[j++]= Pop();
}
}
while(!isEmpty())
postfix[j++]=Pop();
postfix[j] = '\0';
return postfix;
}
int main(){
char *infix = new char[30];
cin>>infix;
cout<<InToPost(infix);
}