zoukankan      html  css  js  c++  java
  • 一.栈

    用来保存数据,遵循先进后出的原则。

    头文件:#include <stack>    声明一个栈 stack<int>s 声明存储int 类型数据的栈s  


    #include <iostream>
    #include <stack>
    using namespace std;
    
    int main()
    {
        stack<int>s;
        cout<<"向栈中插入数据1,2,3"<<endl;
        s.push(1);//s={1}
        s.push(2);//s={1,2}
        s.push(3);//s={1,2,3};
        cout<<"栈顶数据为: "<<s.top()<<endl;
        s.pop();//删除栈顶元素
        cout<<"原来的栈顶数据删除后,新的栈顶数据为: "<<s.top()<<endl;
        s.pop();
        cout<<"原来的栈顶数据删除后,新的栈顶数据为: "<<s.top()<<endl;
        s.pop();
    
        //以下代码和上面执行相同的功能
        for(int i=1;i<=3;i++)
            s.push(i);
        while(!s.empty()) //empty()这个函数来判断栈中是否元素为空
        {
            cout<<s.top()<<endl;
            s.pop();
        }
        return 0;
    }

    执行结果:




    因为后进先出的元素,所以栈用来进制转换很方便

    下面例子是将一个十进制数字转化为2进制数保存在栈中,再从栈中输出。

    #include <iostream>
    #include <stack>
    using namespace std;
    int main()
    {
        int m;
        while(cin>>m)
        {
            stack<int>s;
            while(!s.empty())//现判断一下栈中元素是否为空
                s.pop();
            while(m!=0)
            {
                s.push(m%2);
                m/=2;
            }
            while(!s.empty())
            {
                cout<<s.top();//依次输出栈顶元素
                s.pop();
            }
            cout<<endl;
        }
        return 0;
    }

    运行结果:







  • 相关阅读:
    CF 444B(DZY Loves FFT-时间复杂度)
    摆弄【Nhibernate 协会制图--导乐陪伴分娩】
    固定的报文统计报告的规定
    CSS——(2)与标准流盒模型
    自动复制转换StringBuffer
    IM信息网
    Oracle Redo Log
    【转载】有哪些省时小技巧,是每个Linux用户都应该知道的
    Linux snmp
    MySQL zabbix
  • 原文地址:https://www.cnblogs.com/sr1993/p/3697811.html
Copyright © 2011-2022 走看看