school

thing1's amazing school repo
Log | Files | Refs | Submodules | README

astg.c (952B)


      1 #include <stdlib.h>
      2 #include <stdio.h>
      3 #include <string.h>
      4 
      5 typedef struct ast_node ast_node;
      6 
      7 typedef enum op {
      8 	ADD = 0,
      9 	SUB = 1,
     10 	MUL = 2,
     11 	DIV = 3,
     12 } op;
     13 
     14 typedef struct ast_node {
     15 	op operation;
     16 	int realLeft;
     17 	int realRight;
     18 	ast_node *right;
     19 	ast_node *left;
     20 } ast_node;
     21 
     22 void freeAst(ast_node *head){
     23 	if (head->left != NULL)
     24 		freeAst(head->left);
     25 	if (head->right != NULL)
     26 		freeAst(head->left);
     27 	free(head);
     28 }
     29 
     30 int exec(ast_node *exp){
     31 	if (exp->left != NULL){
     32 		exp->realLeft = exec(exp->left);
     33 		freeAst(exp->left);
     34 		exp->left = NULL;
     35 	}
     36 	if (exp->right != NULL){
     37 		exp->realRight = exec(exp->right);
     38 		freeAst(exp->right);
     39 		exp->right = NULL;
     40 	}
     41 
     42 	if (exp->operation == ADD)
     43 		return exp->realLeft+ exp->realRight;
     44 	if (exp->operation == SUB)
     45 		return exp->realLeft - exp->realRight;
     46 	if (exp->operation == MUL)
     47 		return exp->realLeft * exp->realRight;
     48 	if (exp->operation == DIV)
     49 		return exp->realLeft/ exp->realRight;
     50 	return 0;
     51 }
     52