Pagini recente » Cod sursa (job #2072079) | Rating Dani Daniel (blackeyes99) | Profil eudoarAlberto | Cod sursa (job #205749) | Cod sursa (job #2796640)
#include <stdio.h>
#include <string.h>
template<typename T>
struct Node {
T val;
Node<T>* next = NULL;
Node(T x) {
val = x;
}
};
template<typename T>
struct Stack {
Node<T> *head = NULL;
int size = 0;
void push(T x) {
++size;
if(head == NULL)
head = new Node<T>(x);
else {
Node<T> *temp = head;
head = new Node<T>(x);
head -> next = temp;
}
}
void pop() {
if(size == 0)
return;
--size;
Node<T> *temp = head;
if(head -> next != NULL)
head = head -> next;
delete temp;
}
T top() {
return head -> val;
}
};
bool isDigit(char c) {
if(c >= '0' && c <= '9')
return true;
return false;
}
int priority(char c) {
if(c == '*' || c == '/')
return 2;
if(c == '+' || c == '-')
return 1;
return 0;
}
int operate(int n1, int n2, char op) {
switch(op) {
case '*':
return n1 * n2;
case '/':
return n1 / n2;
case '+':
return n1 + n2;
case '-':
return n1 - n2;
}
return 0;
}
int main() {
char s[100005], operation;
int i, l, n1, n2;
Stack<int> nr;
Stack<char> op;
freopen("evaluare.in", "r", stdin);
freopen("evaluare.out", "w", stdout);
scanf("%s", s);
l = strlen(s);
for(i = 0; i < l; ++i)
if(priority(s[i])) {
while(op.size && priority(s[i]) <= priority(op.top())) {
n2 = nr.top();
nr.pop();
n1 = nr.top();
nr.pop();
operation = op.top();
op.pop();
nr.push(operate(n1, n2, operation));
}
op.push(s[i]);
}
else if(isDigit(s[i])) {
n1 = 0;
while(isDigit(s[i]) && i < l)
n1 = 10*n1 + s[i++] - '0';
--i;
nr.push(n1);
}
else if(s[i] == '(')
op.push('(');
else if(s[i] == ')') {
while(op.size && op.top() != '(') {
n2 = nr.top();
nr.pop();
n1 = nr.top();
nr.pop();
operation = op.top();
op.pop();
nr.push(operate(n1, n2, operation));
}
op.pop();
}
while(op.size) {
n2 = nr.top();
nr.pop();
n1 = nr.top();
nr.pop();
operation = op.top();
op.pop();
nr.push(operate(n1, n2, operation));
}
printf("%d", nr.top());
}