-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathInfixToPostFix.c
115 lines (97 loc) · 2.42 KB
/
InfixToPostFix.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
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define size 20
/* Stack Declaration */
char stack[size];
/* Initializing top to -1 */
int top = -1;
/* function prototype */
void push(char);
char pop();
/* main function */
int main()
{
/* Declaration */
char infix[25], postfix[25];
int len, i, j;
j = -1;
/* Taking an infix expression as input */
printf("Enter a Infix Expression : ");
scanf("%s", infix);
/* len : length of infix expression */
len = strlen(infix);
/* loop starts here */
for(i = 0; i < len; i++)
{
if(infix[i] >= '0' && infix[i] <= '9')
{
postfix[++j] = infix[i];
} else {
if(infix[i] == '(')
{
push(infix[i]);
}
if(infix[i] == ')')
{
char ch = '/';
while(ch != '(')
{
ch = pop();
if(ch != '(')
{
postfix[++j] = ch;
}
}
}
if(infix[i] == '+' || infix[i] == '-' || infix[i] == '*' || infix[i] == '/')
{
char y;
y = stack[top];
if(top == -1 || y == '(' || y < infix[i])
{
push(infix[i]);
}
if(y >= infix[i])
{
postfix[j] = pop();
push(infix[i]);
}
}
}
}
/* for loop end's here */
/* popping elements till stack gets empty (top == -1)*/
while(top != -1)
{
postfix[++j] = pop();
}
/* Displaying postfix expression */
printf("postfix exp : %s\n", postfix);
return 0;
}
/* main function ends here */
/* Function Definition */
/* push() : adds an element into stack and returns nothing */
void push(char ch)
{
if(top==size-1)
{
// stack overflow condition //
printf("Stack is Full!\n");
} else {
stack[++top] = ch;
}
}
/* push function ends here */
/* pop() : remove topmost element in stack and returns element */
char pop()
{
if(top == -1)
{
printf("Stack is Empty!\n");
} else {
return stack[top--];
}
}
/* pop function ends */