-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy path1. Infix to Postfix
135 lines (104 loc) · 1.66 KB
/
1. Infix to Postfix
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
#include<stdio.h>
#include<string.h>
#define STACK_SIZE 40
#define LENGTH 30
void push(char, int*, char[]);
char pop(int*, char[]);
int F(char);
int G(char);
void infix_to_postfix(char[], char[]);
void main()
{
char infix[LENGTH], postfix[LENGTH];
printf("Conversion from infix to postfix\n");
printf("Enter a valid Infix expression\n");
scanf("%s",infix);
infix_to_postfix(infix,postfix);
printf("Converted Postfix expression is:\n%s\n", postfix);
}
void push(char item, int *top, char s[])
{
if(*top == STACK_SIZE - 1)
{
printf("Stack Overflow\n");
return;
}
s[++(*top)] = item;
}
char pop(int *top, char s[])
{
char item_deleted;
if(*top == -1)
return 0;
item_deleted = s[(*top)--];
return item_deleted;
}
int G(char symbol)
{
switch(symbol)
{
case '+':
case '-':
return 1;
case '*':
case '/':
return 3;
case '^':
case '$':
return 6;
case '(':
return 9;
case ')':
return 0;
default:
return 7;
}
}
int F(char symbol)
{
switch(symbol)
{
case '+':
case '-':
return 2;
case '*':
case '/':
return 4;
case '^':
case '$':
return 5;
case '(':
return 0;
case '#':
return -1;
default:
return 8;
}
}
void infix_to_postfix(char infix[],char postfix[])
{
int top, i, j;
char s[STACK_SIZE], symbol;
top = -1;
push('#', &top, s);
j = 0;
for(i = 0; i < strlen(infix); i++)
{
symbol = infix[i];
while(F(s[top]) > G(symbol))
{
postfix[j] = pop(&top, s);
j++;
}
if(F(s[top]) != G(symbol))
push(symbol, &top, s);
else
pop(&top, s);
}
while(s[top] != '#')
{
postfix[j] = pop(&top, s);
j++;
}
postfix[j] = '\0';
}