-
Notifications
You must be signed in to change notification settings - Fork 0
/
check_precedence.c
71 lines (69 loc) · 1.16 KB
/
check_precedence.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
// from the given expression, find the operator with highest priority using stack.
// (consider only basic arithmetic operators)
#include <stdio.h>
#include <string.h>
#define max 50
char stack[max];
int top = -1;
int priority(char ch)
{
int x;
switch (ch)
{
case '+':
case '-':
x = 1;
break;
case '*':
case '/':
x = 2;
break;
}
return x;
}
void push(char ch)
{
top++;
stack[top] = ch;
}
void pop()
{
printf("%c", stack[top]);
top--;
}
int isEmpty()
{
if (top == -1)
{
return 1;
}
else
{
return 0;
}
}
int main()
{
char st[max];
scanf("%[^\n]%*c", st);
for (int i = 0; i < strlen(st); i++)
{
if (st[i] == '+' || st[i] == '-' || st[i] == '*' || st[i] == '/')
{
if (isEmpty())
{
push(st[i]);
}
else if (priority(st[i]) > priority(stack[top]))
{
push(st[i]);
}
else if (priority(st[i]) <= priority(stack[top]))
{
pop();
break;
}
}
}
return 0;
}