On Github AmaanC / dsa-pres
Prepared by Amaan Cheval / @AmaanC
...when I realized I could add GIFs to the slides!
Write the code live, or go through slides?
Definition: Postfix notation is a mathematical notation in which every operator follows all of its operands.
Stack: A last-in-first-out (LIFO) data structure.
Operand: a-z || A-Z || 0-9
Operator: /, *, +, -
Looks complicated. Really, though, it isn't.
Let's convert "a+b*c" to postfix using the rules.
int operand(char c) {
// Returns 0 if c is an operator
// Returns 1 if c is an operand (like a or c)
return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9');
}
int getValueForOperator(char op) {
int val = 0;
switch(op) {
case '/':
val = 4;
break;
case '*':
val = 3;
break;
case '+':
val = 2;
break;
case '-':
val = 1;
break;
default:
val = 0;
break;
}
return val;
}
int higherPrecedence(char op1, char op2) {
// Returns 1 if op1 has higher precedence. 0 otherwise
int val1 = getValueForOperator(op1);
int val2 = getValueForOperator(op2);
return val1 > val2;
}
We can use it this way:
if (higherPrecedence('+', '*')) {
printf("+ is more important than *");
}
char exp[] = "a+b*c";
int i = 0;
char result[10];
int resultI = 0;
while (exp[i] != '\0') {
c = exp[i];
// We now have c, which is the current character.
// All our code goes here, in the middle
i++;
}
if (operand(c)) {
result[resultI] = c;
resultI++;
}
else {
// It is an operator
if (c == '(') {
push(&s, c);
}
// We'll add more here, for the other rules
}
else {
// It is an operator
// Code for previous rules goes here
else if (c == ')') {
temp = pop(&s);
while (temp != '(' && s.top >= 0) {
result[resultI] = temp;
resultI++;
temp = pop(&s);
}
}
}
else {
// It is an operator
// Code for previous rules goes here
else if (s.top < 0 || higherPrecedence(c, seeTop(&s)) || seeTop(&s) == '(') {
push(&s, c);
}
}
else {
// It is an operator
// Code for previous rules goes here
else {
// This means that the operator had a lower precedence than the top of the stack
while (s.top >= 0) {
temp = pop(&s);
result[resultI] = temp;
resultI++;
}
}
}
If there's anything left on the stack, after we're done with all the characters
while (s.top >= 0) {
temp = pop(&s);
result[resultI] = temp;
resultI++;
}
And we're done!