In: Computer Science
(In C)
Note: Can you create an example code of these tasks. use any variables you wish to use.
postfix expressions: (each individual text (T), (F), (NOT), etc is a token)
F T NOT T F NOT T T T AND F T F NAND
(1) Create stack s.
(2) For each token, x, in the postfix expression:
If x is T or F push it into the stack s. (T = true, F = false)
Else if x is a unary operator
i pop an operand, op1, from s
ii compute x op1 (see unary table below)
iii push the result into s
Else if x is a binary operator
i pop an operand, op2, from s
ii pop an operand, op1, from s
iii compute op1 op2 x iv push the result into s
op1 NOT |
!op1 |
Binary operations
op1 op2 AND |
op1 && op2 |
op1 op2 NAND |
!(op1 && op2) |
op1 op2 OR |
op1 || op2 |
op1 op2 NOR |
!(op1 || op2) |
op1 op2 XOR |
op1 ! = op2 |
op1 op2 COND |
!op1 || op2 |
op1 op2 BICOND |
op1 == op2 |
# your code goes here
static int evaluatePostfix(String exp)
{ //We are assuming True as 1 and False as 0 hence creating a stack
of Integer type
//create a stack
Stack<Integer> stack=new Stack<Integer>();
//expression is taken as string ans exp.length() is giving the
length of string
// Scan all characters one by one
for(int i=0;i<exp.length();i++)
{
char c=exp.charAt(i); //giving character present at position
i
// If the scanned character is an operand (number here),
// push it to the stack.
if(Character.isDigit(c))
stack.push(c - '0');
// If the scanned character is an unary operator, pop one
// element from stack apply the operator
else if(c == "!"){
int val = stack.pop();
val = !val;
stack.push(val);
}
/ If the scanned character is a binary operator, pop two
// elements from stack apply the operator
else
{
int val1 = stack.pop();
int val2 = stack.pop();
switch(c)
{
case '&&':
stack.push(val2&&val1);
break;
case '||':
stack.push(val2 || val1);
break;
case '^':
stack.push(val2^val1);
break;
case '==':
stack.push(val2==val1);
break;
}
}
}
return stack.pop();
}