#include <stack> //STL -- stack 头文件 
stack <int> s;   //定义栈 
s.pop();   //从栈顶删除元素; 
s.push();  //从栈顶入栈 
s.top();   //取栈顶元素,但不删除
例:逆波兰式
1 #include <iostream> 2 #include <cstdio> 3 #include <algorithm> 4 #include <stack> 5 //#define ISA_XR 6 using namespace std; 7 stack <int> s; 8 int main() 9 { 10 #ifdef ISA_XR 11 freopen("Reverse_Polish_notation.in","r",stdin); 12 freopen("Reverse_Polish_notation.out","w",stdout); 13 #endif 14 string in; 15 while( cin>>in ) //读入。。。 16 { 17 //读入为符号 则取栈顶两元素进行相应运算 18 if(in[0] == '+') 19 { 20 int a = s.top();s.pop(); 21 int b = s.top();s.pop(); //取栈顶2各元素,赋给a,b,删除两元素 22 s.push(a + b); //运算。。 23 } 24 else if(in[0] == '-') 25 { 26 int a = s.top();s.pop(); 27 int b = s.top();s.pop(); 28 s.push(b - a); 29 } 30 else if(in[0] == '*') 31 { 32 int a = s.top();s.pop(); 33 int b = s.top();s.pop(); 34 s.push(a * b); 35 } 36 else s.push(atoi(in.c_str())); //如果读入为数 则入栈 37 } 38 cout<<s.top(); //输出栈顶元素---最终运算结果; 39 40 #ifdef ISA_XR 41 fclose(stdin); 42 fclose(stdout); 43 #endif 44 return 0; 45 } 46 47
                    
                
                
            
        
浙公网安备 33010602011771号