IntoPostfix C
IntoPostfix C
1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <string.h>
4 #define MAX 100
5 char stack[MAX];
6 char infix[MAX], postfix[MAX];
7 int top = -1;
8
9 void printinfix();
10 void push(char);
11 char pop();
12 int StackIsEmpty();
13 void inToPost();
14 void printpostfix();
15 int precedance(char);
16
17 int main()
18 {
19 printf("enter the infix expression");
20 gets(infix);
21 printinfix();
22 inToPost();
23 printpostfix();
24 return 0;
25 }
26
27 void printinfix()
28 {
29 printf("your expression is :- ");
30 for (int i = 0; i < strlen(infix); i++)
31 {
32 printf(" %c ", infix[i]);
33 }
34 }
35
36 void inToPost()
37 {
38 int i, j = 0;
39 char symbol, next;
40 for (i = 0; i < strlen(infix); i++)
41 {
42 symbol = infix[i];
43 switch (symbol)
44 {
45 case '(':
46 push(symbol);
47 break;
48 case ')':
49 while ((next = pop()) != '(')
50 {
51 postfix[j++] = next;
52 }
53 break;
54 case '+':
55 case '-':
56 case '*':
57 case '/':
58 case '^':
59 while (!StackIsEmpty() && precedance(stack[top]) >= precedance(symbol))
60 {
61 postfix[j++] = pop();
62 }
63 push(symbol);
64 break;
65
66 default:
67 postfix[j++] = symbol;
68 break;
69 }
70 }
71 while (!StackIsEmpty())
72 {
73 postfix[j++] = pop();
74 }
75 postfix[j] = '\0';
76 }
77
78 int precedance(char symbol)
79 {
80 switch (symbol)
81 {
82 case '^':
83 return 3;
84 case '/':
85 case '*':
86 return 2;
87 case '+':
88 case '-':
89 return 1;
90
91 default:
92 return 0;
93 }
94 }
95
96 void printpostfix()
97 {
98 int i = 0;
99 printf("the equivalent expression is:-");
100 while (postfix[i])
101 {
102 printf(" %c ", postfix[i++]);
103 }
104 }
105
106 void push(char c)
107 {
108 if (top == MAX - 1)
109 {
110 printf("stack is overflow");
111 return; // indicates the end of function
112 }
113 top++;
114 stack[top] = c;
115 }
116
117 char pop()
118 {
119 char c;
120 if (top == -1)
121 {
122 printf("stack is empty");
123 exit(1);
124 }
125 c = stack[top];
126 top = top - 1;
127 return c;
128 }
129
130 int StackIsEmpty()
131 {
132 if (top == -1)
133 {
134 return 1;
135 }
136 else
137 return 0;
138 }