1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 | #include <iostream> #include <stack> #include <string.h> using namespace std; char* postfix(char a[]) { int size = strlen(a); char* b = new char[size]; memset(b, '\0', sizeof(char)*size); stack<char> s; int index = 0; for (int i = 0; i < size; i++) { switch (a[i]) { case '+': case '-': while (!s.empty() && s.top() != '(') { b[index++] = s.top(); s.pop(); } s.push(a[i]); break; case '*': case '/': while ( s.top() == '*' || s.top() == '/') { b[index++] = s.top(); s.pop(); } s.push(a[i]); break; case '(': s.push(a[i]); break; case ')': while (s.top() != '(') { b[index++] = s.top(); s.pop(); } s.pop(); break; default: b[index++] = a[i]; } } while (!s.empty()) { if (s.top() != '(' || s.top() != ')') b[index++] = s.top(); s.pop(); } for (int i = 0; i < size; i++) cout << b[i]; return b; } void Evaluation(char* b,int size) { stack<int> s; int temp1 = 0; int temp2 = 0; cout << size; for (int i = 0; i < size; i++) { switch (b[i]) { case '+': temp2 = s.top(); s.pop(); temp1 = s.top(); s.pop(); s.push(temp2 + temp1); break; case '-': temp2 = s.top(); s.pop(); temp1 = s.top(); s.pop(); s.push(temp1 - temp2); break; case '*': temp2 = s.top(); s.pop(); temp1 = s.top(); s.pop(); s.push(temp1 * temp2); break; case '/': temp2 = s.top(); s.pop(); temp1 = s.top(); s.pop(); s.push(temp1 / temp2); break; default: s.push(b[i]-'0'); } } cout << s.top(); } int main() { char a[] = "2+6/2-1"; char* b = postfix(a); Evaluation(b,7); return 0; } | cs |
'자료구조' 카테고리의 다른 글
프로그래밍시 list.. index.. stl error (0) | 2018.12.02 |
---|---|
스택 , 큐, 트리 그리고 깊이탐색과 넓이탐색 (0) | 2018.05.26 |
Double Linked List (0) | 2018.05.26 |
List 자료구조의 기본적 코드 (0) | 2018.05.26 |
두개의 리스트를 합치는 코드 (0) | 2018.05.26 |