Skip to content

Commit 14bba55

Browse files
Create Operator_precedence_using_Stack_ADT.c
1 parent 4af6139 commit 14bba55

File tree

1 file changed

+58
-0
lines changed

1 file changed

+58
-0
lines changed

Operator_precedence_using_Stack_ADT.c

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
// Given an arithmetic expression, find the operator with highest priority using stack.
2+
3+
// (consider only basic arithmetic operators)
4+
5+
#include<stdio.h>
6+
#include<string.h>
7+
char s[20];
8+
int top=-1;
9+
int pri(char c)
10+
{
11+
switch(c)
12+
{
13+
case '+':
14+
case '-':return 1;
15+
break;
16+
case '*':
17+
case '/':return 2;
18+
break;
19+
default: return 0;
20+
}
21+
}
22+
void push(char c)
23+
{
24+
top++;
25+
s[top]=c;
26+
}
27+
char pop()
28+
{
29+
int a=top;
30+
top--;
31+
return s[a];
32+
}
33+
int main()
34+
{
35+
char str[20],temp;
36+
scanf("%[^\n]s",str);
37+
for(int i=0;i<strlen(str);i++)
38+
{
39+
if(str[i]=='+'||str[i]=='-'||str[i]=='*'||str[i]=='/')
40+
{
41+
if(top==-1)
42+
push(str[i]);
43+
else
44+
{
45+
if(pri(s[top])>=pri(str[i]))
46+
{
47+
temp=pop();
48+
push(str[i]);
49+
push(temp);
50+
}
51+
else
52+
push(str[i]);
53+
}
54+
}
55+
}
56+
printf("%c",pop());
57+
return 0;
58+
}

0 commit comments

Comments
 (0)