-
Notifications
You must be signed in to change notification settings - Fork 0
/
12.y
102 lines (94 loc) · 1.22 KB
/
12.y
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
%{
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
int valid=1,top=-1;
struct node
{
char prod[20];
struct node *lt,*rt;
}*n;
struct node *stack[30];
%}
%token digit id
%left '+''-'
%left '*' '/'
%left '(' ')'
%%
E:E'+'E {
createnode("E+E");
n->rt=pop();
n->lt=pop();
push(n);
}
| E'-'E {
createnode("E-E");
n->rt=pop();
n->lt=pop();
push(n);
}
| E'*'E {
createnode("E*E");
n->rt=pop();
n->lt=pop();
push(n);
}
| E'/'E {
createnode("E/E");
n->rt=pop();
n->lt=pop();
push(n);
}
| digit {
createnode("digit");
push(n);
}
| id {
createnode("id");
push(n);
}
|'('E')'{
createnode("(E)");
n->rt=pop();
push(n);
}
%%
push(struct node *n)
{
stack[++top]=n;
}
struct node *pop()
{
return stack[top--];
}
createnode(char prod[])
{
n=(struct node *)malloc(sizeof(struct node));
strcpy(n->prod,prod);
n->lt=n->rt=NULL;
}
void display(struct node *root,int h)
{
int i;
if(root!=NULL)
{
display(root->rt,h+1);
for(i=0;i<h;i++)
printf("\t");
printf("%s\n",root->prod);
display(root->lt,h+1);
}
}
void main()
{
printf("Enter An Expression\n");
yyparse();
createnode("E\n");
n->lt=pop();
push(n);
display(n,1);
}
int yyerror()
{
printf("Invalid String!");
}