zoukankan      html  css  js  c++  java
  • 【STL】栈stack

    栈stack

    头文件与定义                                                                                       

    #include<stack>

    stack<long long>mystack;    //以下以mystack为例

    用法

    1.将元素a入栈:mystack.push(a);

    2.将栈顶元素弹栈/出栈:mystack.pop();

    3.判断栈是否为空:mystack.empty()

    4.栈的长度:cout<<stack.size();

    5.访问栈顶元素:cout<<stack.top();

    注意事项

    1.在出栈或者访问栈顶元素之前应该先判断栈是否为空(或者栈长度是否为0),否则会出错

    2.定义中的<>内不要总是习惯性int。。适当long long

    3.( mystack.empty() ) 是一个判断条件,外围一定要习惯性加上一层(),免得后面再改。

    练习

    http://wikioi.com/problem/3137/

    http://wikioi.com/problem/3138/

    http://wikioi.com/problem/3139/

    三道模板

    对应程序

    //练习1
    #include<iostream>
    #include<stack> 
    using namespace std;
    int n,i,type,a;
    int main()
    {
         stack<int>st;
         cin>>n;
         for (i=1;i<=n;i++)
         {
            cin>>type;
            if (type==1) 
            {
                cin>>a;
                st.push(a);
            }
            if (type==2) st.pop();
         }
         if (st.empty()) {cout<<"impossible!"<<endl;} else {cout<<st.top()<<endl;}
    }
                
    练习1
    //练习2
    #include<iostream>
    #include<stack> 
    using namespace std;
    int n,i,type,a;
    int main()
    {
         stack<long long>st;
         cin>>n;
         for (i=1;i<=n;i++)
         {
            cin>>type;
            if (type==1) 
            {
                cin>>a;
                st.push(a);
            }
            if (type==2) 
            { 
                if (!st.empty()) 
                 {
                        st.pop();
                 }
                else
                 {
                        cout<<"impossible!"<<endl;
                        return 0;
                 }
            }
         }
         if (st.empty()) {cout<<"impossible!"<<endl;} else {cout<<st.top()<<endl;}
         return 0;
    }
    练习2
    //练习3
    #include<iostream>
    #include<stack> 
    using namespace std;
    int n,i,type,a;
    int main()
    {
         stack<long long>st;
         cin>>n;
         for (i=1;i<=n;i++)
         {
            cin>>type;
            if (type==1) 
            {
                cin>>a;
                st.push(a);
            }
            if (type==2) 
            { 
                if (!st.empty()) 
                 {
                        st.pop();
                 }
            }
            if (type==3)
            {
                cout<<st.top()<<endl;
            }
         }
         return 0;
    }
    练习3

    只是为了写STL。。所以不要在意代码的速度啊长度啊什么的。。学STL才是正道。。。

    noip忘记取模的痛
  • 相关阅读:
    IDEA 学习笔记之 Scala项目开发
    IDEA 学习笔记之 Java项目开发
    IDEA 学习笔记之 安装和基本配置
    MongoDB 学习笔记之 索引
    MongoDB 学习笔记之 删除数据,集合,数据库
    Shiro学习(13)RememberMe
    Shiro学习(12)与Spring集成
    Shiro学习(11)缓存机制
    Shiro学习(10)Session管理
    Shiro学习(9)JSP标签
  • 原文地址:https://www.cnblogs.com/seekdreamer/p/3876674.html
Copyright © 2011-2022 走看看