| Код | // author : dargaard // // CFG: // Expr -> term + expr // -> term - expr // -> term // Term -> factor * term // -> factor // Factot -> id // -> ( expr ) //
// // ispolzovanie v inpute (a+b)*c-d*r i t.d. // probeli ne razresheni //
#include <stdio.h> #include <stdlib.h>
// // struktura dlia dereva // struct _node { int chr; struct _node *left; struct _node *right; };
char inp[100]; int inp_ptr; int tok;
void musthave (char); int get_token (); struct _node* parse_input(); struct _node* parse_expr (); struct _node* parse_term (); struct _node* parse_factor (); struct _node* parse_R1 (); void show_tree(struct _node* cur);
struct _node *root;
int main() { struct _node *cur;
inp_ptr = 0; scanf("%s",inp); root = parse_input (); printf("\n\n");
cur = root; show_tree(root); printf("\n"); }
// // vivod dereva // void show_tree(struct _node* cur) { if (cur->chr!=0) printf(" %c ",cur->chr); if (cur->left!=0) show_tree(cur->left); if (cur->right!=0) show_tree(cur->right); }
// // parsim input // struct _node* parse_input () { tok = get_token (); return parse_expr ();
}
// // parsim expr (smotri vishe) // struct _node* parse_expr () { struct _node *new_node = malloc(sizeof(struct _node)); new_node->left = 0; new_node->chr = 0; new_node->right = 0;
new_node->left = parse_term ();
// // Expr -> Term + Expr | Term - Expr // if (tok == '+') { new_node->chr = '+'; musthave ('+'); printf(" + "); new_node->right = parse_expr (); } else if (tok == '-') { new_node->chr = '-'; musthave ('-'); printf (" - "); new_node->right = parse_expr (); } return new_node; }
// // parsim term // struct _node* parse_term () { struct _node *new_node = malloc(sizeof(struct _node)); new_node->chr =0; new_node->left =0; new_node->right =0;
// // Term -> Factor | Factor * Term // new_node->left = parse_factor (); tok = get_token ();
if (tok == '*') { new_node->chr = '*'; musthave ('*'); printf (" * "); new_node->right = parse_term (); } return new_node; }
// // Factor -> id | ( Expr ) // struct _node* parse_factor () { struct _node *new_node = malloc(sizeof(struct _node)); new_node->left = 0; new_node->chr = 0; new_node->right = 0;
if (is_id(tok)) { printf("|%c|",tok); new_node->chr = tok; } else { musthave ('('); printf (" ( "); new_node->left=parse_expr (); printf (" ) "); //tut musthave nenuzhno uzhe //musthave (')'); } return new_node; }
// // poluchaem novii token // int get_token () { inp_ptr++; return inp[inp_ptr-1]; }
void musthave(char c) { if (c != tok) { printf("Error musthave %c got %c\n",c,tok); exit(0); } tok = get_token (); }
int is_id (int c) { if (c >= 'a' && c <= 'z') return 1; return 0; }
|
деление не сделанно  написано под linux но на winde тоже должно работать.
|