-
Notifications
You must be signed in to change notification settings - Fork 3
/
toPostfix.cpp
73 lines (65 loc) · 1.27 KB
/
toPostfix.cpp
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
#include<cstdio>
#include<stack>
using namespace std;
int priority(char); //return operator's priority
int hasHigherPriority(char,char);
//return 0 if op2 has higher priority than op1
//return 1 if otherwise
int main()
{
stack<char> myStack;
char equation[1000];
char* ptr=equation;
printf("input infix: ");
scanf("%s",equation);
while(*ptr!='\0'){
if(*ptr=='(') //manage bracket
{
myStack.push('(');
}
else if(*ptr==')'){
while(myStack.top()!='('){
printf("%c",myStack.top());
myStack.pop();
}
myStack.pop();
}
else if(priority(*ptr)>0) //operator check
{
while(myStack.size()!=0){ //pop until top of stack has lower priority than *ptr or stack is empty
if(hasHigherPriority(myStack.top(),*ptr)==0)
break;
printf("%c",myStack.top());
myStack.pop();
}
myStack.push(*ptr);
}
else //operand
printf("%c",*ptr);
ptr++;
}
//clear stack
while(myStack.size()>0){
printf("%c",myStack.top());
myStack.pop();
}
printf("\n");
return 0;
}
int priority(char op)
{
int r;
switch(op){
case '+':
case '-':r = 1; break;
case '*':
case '/':r = 10; break;
case '^':r = 100; break;
default :r = 0;
}
return r;
}
int hasHigherPriority(char op1,char op2)
{
return priority(op1)>=priority(op2)?1:0;
}