-
Notifications
You must be signed in to change notification settings - Fork 6
/
Program20.c
144 lines (144 loc) · 2.5 KB
/
Program20.c
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
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
#include<stdio.h>
#include<ctype.h>
#include<string.h>
#include<stdlib.h>
#define MAX 100
char stack[MAX],top=-1;
int isOperand(char ch)
{
return (isdigit(ch))||(ch>='a'&&ch<='z')||(ch>='A'&&ch<='Z');
}
int Prec(char ch)
{
switch (ch)
{
case '+':
case '-':
return 1;
case '*':
case '/':
return 2;
case '^':
return 3;
}
return -1;
}
void push(char data)
{
if(top==MAX-1)
printf("\nStack Overflow");
else
stack[++top]=data;
}
char pop()
{
char del;
if(top==-1)
{
printf("\nStack empty");
return '\0';
}
else
{
del=stack[top--];
return del;
}
}
char peek()
{
if(top==-1)
{
printf("\nStack empty");
return '\0';
}
else
{
return stack[top];
}
}
int isEmpty()
{
return (top==-1);
}
char myStr[2];
char* getStr(char ch)
{
myStr[0]=ch;
myStr[1]='\0';
return myStr;
}
void display()
{
if(top==-1)
printf("\nStack empty");
else{
printf("\n");
for(int i=0;i<=top;i++)
{
printf("%c\n",stack[i]);
}
}
}
void strrev(char str[])
{
int n=strlen(str);
for(int i=0;i<n/2;i++)
{
char temp=str[i];
str[i]=str[n-1-i];
str[n-1-i]=temp;
}
}
void infixToPrefix(char exp[],char output[])
{
int i,k,n=strlen(exp);
for(i=n-1;i>=0;i--)
{
if(isOperand(exp[i]))
strcat(output,getStr(exp[i]));
else if(exp[i]==')')
push(exp[i]);
else if(exp[i]=='(')
{
while(peek()!=')')
{
if(isEmpty())
{
printf("Invalid Expression.\n");
exit(0);
}
strcat(output,getStr(pop()));
}
pop();
}
else
{
while(!isEmpty()&&(Prec(peek())>=Prec(exp[i])))
{
strcat(output,getStr(pop()));
}
push(exp[i]);
}
}
while(!isEmpty())
{
if(peek()=='('||peek()==')')
{
printf("Invalid\n");
exit(0);
}
strcat(output,getStr(pop()));
}
strrev(output);
}
int main()
{
char exp[MAX]="(2+3)*4";
printf("Enter a valid Infix Expression : ");
scanf("%s",exp);
char output[MAX];
output[0]='\0';
infixToPrefix(exp,output);
printf("\nPrefix : %s\n",output);
return 0;
}