-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathToPostfix.cpp
More file actions
138 lines (111 loc) · 4.89 KB
/
ToPostfix.cpp
File metadata and controls
138 lines (111 loc) · 4.89 KB
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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
//
// Created by Rainy on 1/22/17.
//
/*
Algorithm: + * () - -> + / -> *
1 操作数输出,操作符入栈
2 比栈顶优先级高则入栈,否则弹出栈顶,直到满足条件
3 (直接入栈,直到遇到),弹出直到(。
4 无操作数,全部出栈
判断: 字符OR数字-》空栈?
*/
#include "ToPostfix.h"
#include "Symbol.h"
#include <iostream>
string Temp;
void ToPostfix::InfixtoPostfix() {
//for(string::iterator i=infix.begin();i<infix.end();++i){
// int isnumber= 0;
// for(string::iterator j=symbol.begin();j<symbol.end();++j){
//if(*i==*j) {
//if (stk.empty())
// stk.push(*i);
//else
string::iterator i = Infix.begin(); //Current Pointer
while(i < Infix.end()){
Temp = *i;
bool IsNumber = true ;
if(Temp == "*") {
while (!stk.empty() && stk.top() == "*") {
Postfix.append(stk.top());
stk.pop(); //Put it out of stack
}
if (stk.empty())
stk.push("*");
if (stk.top() == "+" || stk.top() == "("){ //Unuseful???
stk.push("*"); //Put it into Stack
// cout<<"Get *"<<endl;
}
i += 1;
IsNumber = false;
}
if(Temp == "+"){
while (!stk.empty()&&(stk.top() == "*" || stk.top() == "+")) {
Postfix.append(stk.top());
stk.pop(); //Put it out of stack
}
if (stk.empty())
stk.push("+");
//cout<<"Get +"<<endl;//test
if (!stk.empty() && stk.top() == "(") //Unuseful???
stk.push("+");
i+=1;
IsNumber = false;
}
if(Temp == "(") {
//if (stk.empty())
// stk.push("(");
stk.push("("); //Directly push
i+=1;
IsNumber = false;
}
if(Temp == ")") {
while (!stk.empty() && stk.top() != "(") {
Postfix.append(stk.top());
stk.pop(); //Put it out of stack
}
stk.pop();
i += 1;
IsNumber = false;
}
while (IsNumber) {
Temp = *i;
Postfix.append(Temp);
/*
if(Temp==".") {
Postfix.pop_back();
Postfix.append(Temp);
}
else
Postfix.append(" "+Temp+" ");
*/
//cout<<"Get Number!"<<endl; //test
i += 1;
if(i==Infix.end()){
Postfix.append(" ");
IsNumber = false;
}
else {
for (string::iterator j = Symbol.begin(); j < Symbol.end(); ++j) {
if (*i == *j) {
Postfix.append(" ");
IsNumber = false;
break;
}
}
}
}
cout<<"One Loop"<<endl; //test
}
//All pop
while(!stk.empty()){
Postfix.append(stk.top());
stk.pop();
}
}
void ToPostfix::Display() {
cout<<Postfix<<endl;
}
string ToPostfix::ReturnString() {
return Postfix;
}