Skip to content

Instantly share code, notes, and snippets.

@Kinjalrk2k
Last active March 30, 2019 15:57
Show Gist options
  • Save Kinjalrk2k/bd57b11e074c7e2ced3bec124ef6dbe9 to your computer and use it in GitHub Desktop.
Save Kinjalrk2k/bd57b11e074c7e2ced3bec124ef6dbe9 to your computer and use it in GitHub Desktop.
This piece of code evaluates an post-fix expression using Stack. Highly undocumented! Ask if in Doubt!
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <limits.h>
#include <math.h>
struct node{
float data;
struct node *next;
};
struct node *head = NULL;
void push(float data){
if (head == NULL) {
head = (struct node *)malloc(sizeof(struct node));
if (head == NULL) {
printf("Memory Underflow! Insertion failed!");
return;
}
head->data = data;
head->next = NULL;
return;
}
struct node *newNode = (struct node *)malloc(sizeof(struct node));
if (newNode == NULL) {
printf("Memory Underflow! Insertion failed!");
return;
}
else {
struct node *ptr = head;
while(ptr->next != NULL){
ptr = ptr->next;
}
newNode->data = data;
newNode->next = NULL;
ptr->next = newNode;
}
}
float pop(){
if (head == NULL) {
printf("List underflow! Unable to delete!");
return INT_MIN;
}
struct node *ptr = head, *ptr_prev;
while(ptr->next != NULL){
ptr_prev = ptr;
ptr = ptr->next;
}
ptr_prev->next = NULL;
float popped = ptr->data;
free(ptr);
return popped;
}
int isOperator(char ch) {
char optlist[] = "+-*/^";
for(int i=0; i<strlen(optlist); i++)
{
if(ch == optlist[i])
return 1;
}
return 0;
}
int isOperand(char ch) {
if(ch >= '0' && ch <= '9')
return 1;
return 0;
}
float operation(float a, float b, char op)
{
switch(op)
{
case '+': return b+a; break;
case '-': return b-a; break;
case '*': return b*a; break;
case '/': return b/a; break;
case '^': return pow(b,a); break;
default: return INT_MIN;
}
}
float EvalPostfix(char* postfix)
{
float a, b;
push(INT_MIN);
for(int i=0; i<strlen(postfix); i++)
{
if(isOperator(postfix[i]))
{
a = pop();
b = pop();
push(operation(a, b, postfix[i]));
}
else if(isOperand(postfix[i]))
{
int j = i, k = 0;
char str_num[10];
while(postfix[j] != ',')
{
str_num[k] = postfix[j];
k++;
j++;
}
str_num[k] = '\0';
int num = atoi(str_num);
push(num);
i = j;
}
else if(postfix[i] == ',')
continue;
}
float res = pop();
return res;
}
int main()
{
char postfix[] = "5,6,2,+,*,12,4,/,-";
float ans = EvalPostfix(postfix);
printf("Answer: %lf\n", ans);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment