-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinfix_to_prefix_array.c
More file actions
116 lines (116 loc) · 2.75 KB
/
Copy pathinfix_to_prefix_array.c
File metadata and controls
116 lines (116 loc) · 2.75 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
115
116
#include <stdio.h>
#define max 100
char stack[max];
int top=-1;
void push(char stack[], int val);
char pop(char stack[]);
void infixtopostfix(char source[], char target[]);
int getpriority(char op);
void reverse(char stack[]);
int main(){
char infix[100], postfix[100];
printf("Enter infix expression");
gets(infix);
printf("Your infix expression is : ");
puts(infix);
infixtopostfix(infix, postfix);
printf("\nPostfix expression is : ");
puts(postfix);
reverse(infix);
infixtopostfix(infix, postfix);
printf("\nCorresponding Postfix expression is : ");
puts(postfix);
reverse(postfix);
printf("\nPrefix expression is : ");
puts(postfix);
return 0;
}
void push(char stack[], int val){
if(top==max-1){
printf("Overflow");
}
else{
top++;
stack[top]=val;
}
}
char pop(char stack[]){
char val;
if(top==-1){
printf("underflow");
}
else{
val=stack[top];
top--;
}
return val;
}
void infixtopostfix(char source[], char target[]){
int i=0, j=0;
char temp;
while(source[i]!='\0'){
if(source[i]=='('){
push(stack, source[i]);
i++;
}
else if(source[i]==')'){
while((top!=-1) && (stack[top]!='(')){
target[j]=pop(stack);
j++;
}
if(top==-1){
printf("Incorrect expression");
exit(1);
}
temp=pop(stack);
i++;
}
else if((source[i]>='0' && source[i]<='9') || (source[i]>='A' && source[i]<='Z') || (source[i]>='a' && source[i]<='z')){
target[j]=source[i];
j++;
i++;
}
else if(source[i]=='+' || source[i]=='-' || source[i]=='*' || source[i]=='/' || source[i]=='%'){
while((top!=1) && (source[i]!='(') && (getpriority(stack[top])>getpriority(source[i]))){
target[j]=pop(stack);
j++;
}
push(stack, source[i]);
i++;
}
else{
printf("Incorrect element in expression");
exit(1);
}
}
while((top!=-1) && (stack[top]!='(')){
target[j]=pop(stack);
j++;
}
target[j]='\0';
}
int getpriority(char op){
if(op=='+' || op=='-'){
return 0;
}
else if(op=='*' || op=='/' || op=='%'){
return 1;
}
}
void reverse(char stack[]){
int i=0, x=strlen(stack);
char temp;
for(i=0; i<=x/2; i++){
temp=stack[i];
stack[i]=stack[x-i-1];
stack[x-i-1]=temp;
}
for(i=0; i<=x/2; i++){
if(stack[i]=='('){
stack[i]=')';
}
else if(stack[i]==')'){
stack[i]='(';
}
}
}