栈
// 栈
stack<int> mystack; //栈的定义
// 栈的状态:
mystack.empty();//是否为空
mystack.size();//长度
//mystack.push(int x) 入栈
//mystack.pop() 出栈
//由于栈只能在栈顶进行操作,所以对元素的访问为:
mystack.top();
//Zero-complexity Transposition 上交机试
int n;
stack<long long> sequence;
while(cin >> n){
while(n--){
long long number;
cin >> number;
sequence.push(number);
}
while(!sequence.empty()){
cout << sequence.top() << " ";
sequence.pop();
}
cout <<endl;
}
// 括号匹配问题
// string str;
// while(cin >> str){
// string w(str.size(),' ');
// stack<int> q;
// for(int i = 0;i < str.size();i++){
// if(str[i] == '('){
// q.push(i);
// }else if(str[i] == ')'){
// if(!q.empty()){
// q.pop();
// }else{
// w[i] = '?';
// }
// }
// }
// while(!q.empty()){
// w[q.top()] = '$';
// q.pop();
// }
// cout << str << endl;
// cout << w << endl;
// }
思路:
(1)两个栈,符号栈和数字栈。两个哨兵'#'和'¥','#'压入栈底,'¥'接在串后,优先级'¥'>'#'。
(2)优先级获得函数:'#'=0,'¥'=1,'+''-'=2,'*''/'=3。
(3)获取数字函数
(4)加减乘除计算函数
(5)遍历字符串,遇到空格则跳过;遇到数字则压入数字栈;
如果遇到的是符号,则比较当前op与操作符栈顶opTop的优先级
1)若果op>opTop,则将op入栈
2)如果op<=opTop,则弹出opTop,并弹出数字stack的栈顶和次栈顶,次栈顶为参与运算的在前数字,栈顶数字在后。
计算结果存入数字stack。
(6)直到遍历结束,此时操作符stack中只剩'¥''#',且此时数字stack中只剩一个元素,即为结果。
int Priority(char c){
if (c == '#'){
return 0;
}else if (c == '$'){
return 1;
}else if (c == '+'|| c == '-'){
return 2;
}else{
return 3;
}
}
double GetNumber(string str,int& index){//int& 为引用型,可以改变传递过来的参数本身的值,它们指向同一地址
double number = 0;
while(isdigit(str[index])){
number = number*10 + str[index]-'0';//注意char转为int
index++;
}
return number;
}
double Calculate(double x,double y,char op){
double result = 0;
if(op=='+'){
result= x+y;
}else if(op=='-'){
result= x-y;
}else if(op=='*'){
result= x*y;
}else if(op=='/'){
result= x/y;
}
return result;
}
int main(){
string str;
while(getline(cin,str)){
if(str == "0"){
break;
}
int index = 0;
stack<char> oper;
stack<double> data;
str += "$";
oper.push('#');
while(index < str.size()){
if(str[index]==' '){
index++;
}else if(isdigit(str[index])){
data.push(GetNumber(str,index));//注意这里不用自增,在函数中已经自增
}else{
if(Priority(str[index])>Priority(oper.top())){
oper.push(str[index++]);
}else{
double y = data.top();
data.pop();
double x = data.top();
data.pop();
data.push(Calculate(x,y,oper.top()));
oper.pop();
}
}
}
printf("%.2f\n",data.top());
}
return 0;
}