kar7mp5

[자료 구조] 후위 표기법 연산 C++ 본문

전공/자료구조

[자료 구조] 후위 표기법 연산 C++

kar7mp5 2024. 3. 22. 11:57
728x90
#include <iostream>
using namespace std;

#define endl '\n'

struct Node {
    int val;
    Node* next;
};


class LinkedList {
public:
    LinkedList();
    int getSize() const;
    bool isEmpty() const;
    int getTop() const;
    void push(const int& _val);
    int pop();

private:
    Node* head;
    Node* tail;
    int size;
};

LinkedList::LinkedList() {
    head = nullptr;
    tail = nullptr;
    size = 0;
}

int LinkedList::getSize() const {
    return size;
}

bool LinkedList::isEmpty() const {
    if (size == 0)
        return 1;
    else
        return 0;
}

int LinkedList::getTop() const {
    if (isEmpty()) {
        return -1;
    }
    return head->val;
}

void LinkedList::push(const int& _val) {
    Node* newNode = new Node;
    newNode->val = _val;
    ++size;
    if (isEmpty()) {
        head = newNode;
        tail = newNode;
    }
    else {
        Node* tmp = head;
        head = newNode;
        head->next = tmp;
    }
}

int LinkedList::pop() {
    if (isEmpty()) {
        return -1;
    }
    Node* tmp = head->next;
    int result = head->val;
    delete head;
    head = tmp;
    --size;
    return result;
}


int main() {
    ios::sync_with_stdio(0);
    cin.tie(0); cout.tie(0);

    int N;
    cin >> N;
    
    LinkedList* List = new LinkedList;

    string input;
    for (int i = 0; i < N; ++i) {
        cin >> input;
        for (int j = 0; j < input.size(); ++j) {
            if (input[j] >= '0' && input[j] <= '9') {
                List->push(input[j] - '0');
            }
            else {
                if (input[j] == '+') {
                    int x = List->getTop();
                    List->pop();
                    int y = List->getTop();
                    List->pop();
                    List->push(y + x);
                }
                else if (input[j] == '-') {
                    int x = List->getTop();
                    List->pop();
                    int y = List->getTop();
                    List->pop();
                    List->push(y - x);
                }
                else if (input[j] == '*') {
                    int x = List->getTop();
                    List->pop();
                    int y = List->getTop();
                    List->pop();
                    List->push(y * x);
                }
            }
        }
        int result = List->getTop();
        List->pop();

        int sum = 0;
        while (result) {
            sum += result % 10;
            result /= 10;
        }

        if (sum < 0) {
            sum *= -1;
        }

        cout << sum << endl;
    }

    return 0;
}
728x90