spoj:ONP - 转换表达式

时间:2015-12-19 19:59:26

标签: c++ algorithm

我正在尝试解决一个问题:link 它显示运行时错误,测试用例在我的机器上工作正常。我无法弄清楚程序中的错误。我正在使用队列和堆栈来实现它。

编辑:我已经编辑了源代码,并在pop函数中修正了int temp - > char temp ..但是我仍然遇到运行时错误;

 #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;
}

1 个答案:

答案 0 :(得分:1)

您是否认为表达式的大小与队列和堆栈的主要不匹配大小

有关

在pop函数中,您已将temp声明为int,而返回类型为char