-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathProg4(StackImplement).c
79 lines (73 loc) · 1.51 KB
/
Prog4(StackImplement).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
/*
Design, Develop and Implement a Program in C for converting an Infix Expression to Postfix
Expression. Program should support for both parenthesized and free parenthesized
expressions with the operators: +, -, *, /, % (Remainder), ^ (Power) and alphanumeric
operands.
*/
#include <stdio.h>
#include <ctype.h>
#define max 20
char infix[max], postfix[max], stack[max];
int top = -1;
int precedence(char ch);
void push(char ch)
{
stack[++top] = ch;
}
char pop()
{
return (stack[top--]);
}
int precedence(char ch)
{
switch (ch)
{
case '#':
return 0;
case '(':
return 1;
case '-':
case '+':
return 2;
case '*':
case '/':
case '%':
return 3;
case '^':
return 4;
}
}
void main()
{
char ch, elem;
int k = 0, i = 0;
printf("\nEnter infix expression: ");
gets(infix);
puts(infix);
push('#');
while ((ch = infix[i++]) != '\0')
{
if(isalnum(ch))
postfix[k++] = ch;
else if(ch == '(')
push(ch);
// else if(ch == ' ')
// i++;
else if(ch == ')')
{
while(stack[top] != '(')
postfix[k++] = pop();
elem = pop();
}
else // operator
{
while(precedence(stack[top]) >= precedence(ch))
postfix[k++] = pop();
push(ch);
}
}
while(stack[top] != '#')
postfix[k++] = pop();
postfix[k] = '\0';
printf("\nINFIX : %s\nPOSTFIX: %s",infix, postfix);
}