2 / 2
Mar 2018

#define max1 50
#include
#include<ctype.h>
using namespace std;
class stack1
{
char stack2[max1];
int top;
public:
stack1()
{
top=-1;
}
int push(char);
char pop();
char value()
{
if(top!=-1)
return stack2[top];
else
return’\0’;
}
};
int stack1::push(char a)
{
if(top==max1)
{
return -1;
}
else
{
top++;
stack2[top]=a;
return 1;
}
}
char stack1::pop()
{
char a;
if(top==-1)
return ‘\0’;
else
{
a=stack2[top];
top–;
return a;
}
}
int priority(char a)
{
if(a==’*’)
return 2;
if(a==’/’)
return 2;
if(a==’(’ || a==’)’)
return 0;
if(a==’+’ || a==’-’)
return 1;
if(a==’^’)
return 3;
}
int main()
{
int count1=0;
int count2=0;
char b;
int n,i;
cout<<"\nenter the no of test cases";
cin>>n;
stack1 s[n];
char d[n][max1];
for(i=0;i<n;i++)
{
string s1;
cout<<"\nenter the string";
cin>>s1;
while(s1[count1]!=’\0’)
{
b=s1[count1];
if(isalpha(b))
{
d[i][count2++]=b;
count1++;
}
else
{
if(b==’(’)
{
s[i].push(b);
count1++;
}
else if(b==’)’)
{
char e;
e=s[i].pop();
while(e!=’(’)
{
d[i][count2++]=e;

                   e=s[i].pop();
                }
                count1++;
            }
            else
            {
                char e;
                e=s[i].value();
                while(e!='\0')
                {
                    if(priority(e)>priority(b))
                    {
                        e=s[i].pop();
                        d[i][count2++]=e;
                    }
                    else
                    {
                        break;
                    }
                    e=s[i].value();
                }
                s[i].push(b);
                count1++;
            }
        }
}
while(s[i].value()!='\0')
{
    d[i][count2++]=s[i].pop();
}
d[i][count2]='\0';
count1=0;
count2=0;

}
cout<<"\n";
count1=0;
char a;
for(i=0;i<n;i++)
{
a=d[i][count1];
while(a!=’\0’)
{
cout<<a;
count1++;
a=d[i][count1];
}
cout<<"\n";
count1=0;
}
}

  • created

    Mar '18
  • last reply

    Mar '18
  • 1

    reply

  • 609

    views

  • 2

    users

I don’t get a sigsegv with your code, but I do find wrong answers. For example, try the below. You give the same answer for both, yet they should obviously be different.

2
(ab-c+d)
(a
b-(c+d))

BTW, you shouldn’t be writing prompts like “enter the no of test cases” and “enter the string”. These will go into your program’s output and cause a WA.

Suggested Topics

Topic Category Replies Views Activity
C and C++ 0 17 10d

Want to read more? Browse other topics in C and C++ or view latest topics.