使用堆栈将中缀转换为Postfix

时间:2016-07-18 21:56:32

标签: c++11 stack operator-keyword postfix-notation infix-notation

我在创建将中缀转换为后缀的程序时遇到问题。我的代码如下:

#include <iostream>
#include <string>
#include <sstream>

using namespace std;

#define DEFAULT_SIZE 20

/*
*
*/

class Stack {
    char *arr;
    int tos, capacity;
public:
    //Constructors
    Stack();
    Stack(int size);

    //Destructor
    ~Stack();

    //Methods
    void push(char a);
    char pop();
    int get_size();
    bool is_empty();
    bool is_full();
    void display();
    char get_top();


};


Stack::Stack() {
    arr = new char[DEFAULT_SIZE];
    tos = 0;
    capacity = DEFAULT_SIZE;
}

Stack::Stack(int size) {
    arr = new char[size];
    tos = 0;
    capacity = size;
}

Stack::~Stack() {
    delete[] arr;
}

void Stack::push(char a) {
    if (!is_full())
        arr[tos++] = a;
    else
        cout << "Sorry, the stack is full. Push failed!" << endl;

}
char Stack::pop() {
    if (!is_empty())
        return arr[--tos];
    else {
        cout << "Sorry, the stack is empty. Pop failed!" << endl;
        return -1;
    }


}


char Stack::get_top() {
    if (!is_empty())
        return arr[tos - 1];
    else {
        cout << "Sorry, the stack is empty. Pop failed!" << endl;
        return 'E';
    }
}


int Stack::get_size() {
    return tos;

}
bool Stack::is_empty() {
    if (tos == 0)
        return true;
    else
        return false;


}
bool Stack::is_full() {
    if (tos == capacity)
        return true;
    else
        return false;

}

void Stack::display() {
    if (tos == 0)
        cout << "The stack is empty" << endl;
    else {
        for (int i = 0; i<tos;i++)
            cout << arr[i] << " ";
        cout << endl;
    }


}

int main() {
    Stack stack(50);
    string infix = "(1+3)*2/(6-4)^2";
    stringstream ss;


    for (char c : infix) {
        if ('0' <= c && c <= '9') {
            ss << c;
        }
        else if (c == '(') {
            continue;

        }
        else if (c == ')') {
            ss << stack.pop();
            stack.pop();
        }

        else if (c == '^' || c == '*' || c == '/' || c == '+' || c == '-') {
            stack.push(c);
        }

    }

    string postfix = ss.str();
    cout << postfix;

我知道我的问题是什么,我只是不理解或理解如何解决它。此代码目前输出13 + 264-2。它需要输出13 + 2 * 64-2 ^ /。我知道我的问题与else if中我的上一个int main()声明有关。我不明白如何重新排列操作数背后的运算符。

括号中的任何内容都会正确传递到流中,因为我可以等到命中右括号以在运算符中添加。我无法想象如何为不在括号中的事情做出贡献。有人可以提供任何建议吗?

0 个答案:

没有答案
相关问题