Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- using namespace std;
- struct Stack{
- private :
- char stack[150];
- int size=0;
- public:
- void push(char a){
- size++;
- stack[size]=a;
- }
- char pop(){
- size--;
- return stack [size+1];
- }
- char top(){
- return stack[size];
- }
- int getSize()
- {
- return size;
- }
- };
- struct numStack{
- private :
- int stackOfNum[150];
- int sizeNum=0;
- public:
- void push(int a){
- sizeNum++;
- stackOfNum[sizeNum]=a;
- }
- int pop(){
- sizeNum--;
- return stackOfNum[sizeNum+1];
- }
- int top(){
- return stackOfNum[sizeNum];
- }
- int getSizeNum()
- {
- return sizeNum;
- }
- };
- int priority(char op){
- if(op=='(')return 1;
- if(op=='+'||op=='-')return 2;
- if(op=='*'||op=='/')return 3;
- if(op=='^')return 4;
- }
- string polNot(string notation){
- string result ="";
- Stack operation;
- int i;
- for(i = 0; i<notation.size(); i++){
- if (notation[i]>='0'&& notation[i]<='9'){
- result.push_back(notation[i]);
- }
- else
- {
- if(notation[i]=='('){
- operation.push('(');
- }
- else{
- if(notation[i]==')'){
- while(operation.top() != '(')
- result.push_back(operation.pop());
- operation.pop();
- }
- else
- if(operation.getSize()==0 || priority(notation[i])>priority(operation.top())){
- operation.push(notation[i]);
- }
- else{
- while(operation.getSize()>0 && priority(notation[i])<= priority(operation.top())){
- result.push_back(operation.pop());
- }
- operation.push(notation[i]);
- }
- }
- }
- }
- while(operation.getSize()>0){
- result.push_back(operation.pop());
- }
- return result;
- }
- string str;
- numStack numberStack;
- int resultat(string str){
- for(int i = 0; i< str.size(); i++)
- if(str[i] >= '0' && str[i]<='9'){
- numberStack.push(str[i]-'0');
- }
- else {
- int a,b;
- a = numberStack.top();
- numberStack.pop();
- b = numberStack.pop();
- numberStack.pop();
- if(str[i]=='+') numberStack.push(b + a);
- if(str[i]=='-') numberStack.push(b - a);
- if(str[i]=='*') numberStack.push(b * a);
- if(str[i]=='/') numberStack.push(b / a);
- if(str[i]=='^') numberStack.push(b ^ a);
- }
- return numberStack.top();
- };
- int main(){
- string s;
- cout << "Enter exercise: ";
- cin >> s;
- string polka = polNot(s);
- cout << "Result = " << resultat(polka);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement