-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathInfixToPrefixRE.c
More file actions
114 lines (103 loc) · 3.19 KB
/
InfixToPrefixRE.c
File metadata and controls
114 lines (103 loc) · 3.19 KB
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
103
104
105
106
107
108
109
110
111
112
113
114
/******************************************************************************************
* Visit https://github.com/biabbas/InfixToPrefix for all files. *
* *
* *
* *
* *
* *
* Created by B I *
******************************************************************************************/
#include <stdio.h>
#include <ctype.h>
#include <stdlib.h>
#include <string.h>
typedef struct node{
char a;
struct node* ptr;
} * Node;
Node attach(Node f, Node l);
int ip(char x);
Node getNode(char x);
void prefix(char in[]);
int main(int argc, const char * argv[]) {
char in[20];
printf("Enter the valid expression:\n");
scanf("%s",in);
in[strlen(in)]='\0';
prefix(in);
return 0;
}
Node attach(Node f, Node l){
Node temp = f;
while(temp->ptr!= NULL)
temp = temp->ptr;
temp->ptr = l;
return f;
}
int ip(char x){
switch (x) {
case '#' :
case '(' : return 0;
case '+' :
case '-' : return 1;
case '*' :
case '/' : return 2;
case '$' :
case '^' : return 3;
default: return 0;
}
}
Node getNode(char x){
Node temp = (Node)malloc(sizeof(struct node));
temp->a = x;
temp->ptr = NULL;
return temp;
}
void prefix(char in[]){
int to = 0, tn = -1,i =0;
Node OpStk[10], Stk[10],temp;
OpStk[to] = getNode('#');
while(in[i]!= '\0'){
temp = getNode(in[i++]);
if(isalnum(temp->a)){
Stk[++tn] = temp;
}
else if (temp->a=='(')
OpStk[++to]=temp;
else if (temp->a==')'){
while(OpStk[to]->a != '('){
Stk[tn-1] = attach(Stk[tn-1],Stk[tn]);
tn--;
Stk[tn] = attach(OpStk[to--],Stk[tn]);
}
free(temp);
free(OpStk[to--]);
}
else{
if(ip(OpStk[to]->a) < ip(temp->a))
OpStk[++to] = temp;
else{
while(ip(OpStk[to]->a) >= ip(temp->a)){
Stk[tn-1] = attach(Stk[tn-1],Stk[tn]);
tn--;
Stk[tn] = attach(OpStk[to--],Stk[tn]);
}
OpStk[++to] = temp;
}
}
}
while(to!=0){
Stk[tn-1] = attach(Stk[tn-1],Stk[tn]);
tn--;
Stk[tn] = attach(OpStk[to],Stk[tn]);
to--;
}
free(OpStk[to]);
printf("\n");
temp = Stk[tn];
while(temp!= NULL){
printf("%c", temp->a);
temp = temp->ptr;
}
printf("\n");
}