-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathtoPrefix.cpp
75 lines (70 loc) · 1.27 KB
/
toPrefix.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
74
75
#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;
stack<char> solution;
char equation[1000];
char* ptr=equation;
printf("input infix: ");
scanf("%s",equation);
while(*ptr!='\0')ptr++;
ptr--;
while(ptr>=equation){
if(*ptr==')')
{
myStack.push('(');
}
else if(*ptr=='('){
while(myStack.top()!='('){
solution.push(myStack.top());
myStack.pop();
}
myStack.pop();
}
else if(priority(*ptr)>0)
{
while(myStack.size()!=0){
if(hasHigherPriority(myStack.top(),*ptr)==0)break;
solution.push(myStack.top());
myStack.pop();
}
myStack.push(*ptr);
}
else
solution.push(*ptr);
ptr--;
}
while(myStack.size()>0){
solution.push(myStack.top());
myStack.pop();
}
while(solution.size()>0){
printf("%c",solution.top());
solution.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;
}