-
Notifications
You must be signed in to change notification settings - Fork 0
/
dslab_4.c
92 lines (90 loc) · 1.78 KB
/
dslab_4.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
#include<stdio.h>
#include<stdlib.h>
#include<ctype.h>
#define max 20
char stack[max],postfix[30],infix[30],c,elem;
int top=-1,i=0,j=0,flag;
int precidence(char ch)
{
switch(ch)
{
case '#':return 0;
break;
case '(':return 1;
break;
case '+':return 2;
break;
case '-':return 2;
break;
case '*':return 3;
break;
case '/':return 3;
break;
case '%':return 3;
break;
case '^':return 4;
break;
default:printf("wrong expression\n");
exit(0);
break;
}
}
void push(char ch)
{
stack[++top]=ch;
}
char pop()
{
return(stack[top--]);
}
void main()
{
printf("enter the infix expression\n");
scanf("%s",infix);
stack[++top]='#';
while((c=infix[i++])!='\0')
{
if(c=='(')
{
push(c);
}
else if(isalnum(c))
{
postfix[j++]=c;
}
else if(c==')')
{
if(stack[top]=='#')
{
printf("invalid expression\n");
flag=0;
}
else
{
while(stack[top]!='(')
{
postfix[j++]=pop();
}
elem=pop();
}
}
else
{
int p=precidence(c);
if(c=='^')
{
p++;
}
while(precidence(stack[top])>=p)
{
postfix[j++]=pop();
}
push(c);
}
}
while(stack[top]!='#')
{
postfix[j++]=pop();
}
printf("postfix expression is %s\n",postfix);
}