Reputation: 534
I am trying to solve a spoj problem : link it is showing run time error, the test cases are working fine on my machine. not able to figure out the bug in my program.I am using a queue and stack to implement it.
Edit: i have edited the source code, and rectified int temp-->char temp in pop function.. but still i am getting a run time error;
#include <iostream>
using namespace std;
int top = -1;
int endQueue = -1;
char stack[505];
char queue[505];
int pref(char a) {
switch (a) {
case '+':
case '-' :return 1;
break;
case '*' :
case '/' :return 2;
break;
case '^' :return 3;
break;
default: return 0;
}
}
void push(char a) {
if (top < 0)
top =0;
stack[++top] = a;
}
char pop() {
char temp = stack[top];
top--;
return temp;
}
void enque(char a) {
if (endQueue < 0)
endQueue = 0;
queue[++endQueue] = a;
}
char topElement() {
if (top > -1)
return stack[top];
else
return '0';
}
int main() {
// your code here
int t;
char temp;
char exp[500];
cin>>t;
while(t--) {
cin>>exp;
//cout<<exp;
for (int i = 0; exp[i]!= '\0';i++) {
if (exp[i]>= 'a' && exp[i] <='z') {
// variables\
enque(exp[i]);
} else {
//operator
if (exp[i] == ')') {
// pop till (
// and append
while (top > -1 ) {
temp = pop();
if (temp == '(')
break;
else
enque(temp);
}
} else {
while (exp[i] != '(' && top > -1 && pref(topElement()) > pref(exp[i]) ) {
char popped = pop();
enque(popped);
}
push(exp[i]);
}
}
}
while(top > -1) {
enque(pop());
}
for (int j = 0;j<=endQueue;j++) {
cout<<queue[j];
}
cout<<"\n";
}
return 0;
}
Upvotes: 2
Views: 1239
Reputation: 952
Don't you think the size of your expression in main mismatches size of the queue and stack
And in pop function you have declared temp as int while return type is char
Upvotes: 1