DSA Practical 2
DSA Practical 2
#include <iostream>
#include <string> #include<math.h>
using namespace std;
char pop() {
if (isEmpty()) { cout << "Stack
is empty!" << endl;
return '\0';
}
char poppedData = top->data;
Node* temp = top; top = top-
>next; delete temp; return
poppedData;
}
private:
Node* top; };
if (isOperand(ch)) {
postfix += ch; } else
if (ch == '(')
{ stack.push(ch);
} else if (ch == ')') {
while (!stack.isEmpty() && stack.peek() != '(') {
postfix += stack.pop();
}
stack.pop(); // Pop the '('
} else {
while (!stack.isEmpty() && precedence(ch) <= precedence(stack.peek()))
{ postfix += stack.pop();
}
stack.push(ch);
}
}
while (!stack.isEmpty()) {
postfix += stack.pop();
}
return postfix;
}
if (isOperand(ch)) {
stack.push(ch - '0'); // Convert character to integer
} else { int op2 =
stack.pop(); int op1 =
stack.pop();
int result;
switch (ch)
{ case '+':
result = op1 + op2;
break;
case '-':
result = op1 - op2;
break;
case '*': result =
op1 * op2;
break;
case '/':
result = op1 / op2;
break;
case '^':
result = pow(op1, op2);
break; default:
cout << "Invalid operator!" << endl;
return 0;
}
stack.push(result);
}
}
return stack.pop();
}
return 0;
}
Output:-