stack的常见用法详解

stack的常见用法详解

说在前面:

stack翻译为,是STL中实现的一个后进先出的容器。要使用 stack,应先添加头文件include

  1. stack的定义

  2. stack容器内元素的访问与常用函数实列解析

  3. stack常见用途

  • [x] stack的定义

    其定义的写法和其他STL容器相同, typename可以任意基本数据类型或容器:

    stack<typename> name;
    
  • [x] stack容器内元素的访问与常用函数实列解析

    1. 先出的数据结构,在STL的 stack中只能通过top()来访问栈顶元素。
    2. push(x)将x入栈,时间复杂度为O(1),实例见“ stack容器内元素的访问。
    3. top()获得栈顶元素,时间复杂度为O(1),实例见“ stack容器内元素的访问。
    4. pop()用以弹出栈顶元素,时间复杂度为O(1)。
    5. empty()可以检测stack是否为空,返回true为空,返回false为非空,时间复杂度为O(1)。
    6. size()返回stack内元素的个数,时间复杂度为O(1)。
    #include <iostream>
    #include <stack>
    using namespace std;
    int main()
    {
        stack<int> s;
        int t;
        for (int i=1;i<5;i++)
        {
            t=i;
            s.push(t);   //  压栈
        }
        while(!s.empty())  //  判断非空
        {
            cout<<s.top();  //  打印顶部元素
            s.pop();        //  移除栈顶元素
            if(s.size()!=0)  //  测栈中元素的多少;
                cout<<" ";
        }
        cout<<endl;
        return 0;
    }
    // 输出:
    4 3 2 1
    
  • [x] stack常见用途

  • stack用来模拟实现一些递归,防止程序对栈内存的限制而导致程序运行出错。一般来说,程序的栈内存空间很小,对有些题目来说,如果用普通的函数来进行递归,一旦递归层数过深(不同机器不同,约几千至几万层),则会导致程序运行崩溃。如果用栈来模拟递归算法的实现,则可以避免这一方面的问题(不过这种应用出现较少)。

下面我举几个实例来展示stack的用法示例

  • 10进制转二进制

    可以通过栈这个数据结构实现

    #include <iostream>
    #include <stack>
    using namespace std;
    stack<int> s;    //  储存每一次对2取余的结果
    void turn (int t)
    {
        while(t!=0)
        {
            s.push(t%2);
            t/=2;
        }
    }
    int main()
    {
        int t;
        while(cin>>t)
        {
            turn (t);
            while(!s.empty())
            {
                cout<<s.top();
                s.pop();
            }
            cout<<endl;
        }
        return 0;
    }
    
  • 将字符串逆序输出

    例如将 str="nice to meet you @ qiuqiu"逆序输出。

    #include <iostream>
    #include <stack>
    #include <sstream>
    using namespace std;
    int main()
    {
        string str("nice to meet you @ qiuqiu"),tmp;
        stack<string> s;
        stringstream ss;
        ss<<str;
        while(ss>>tmp)
        {
            s.push(tmp);
        }
        while(!s.empty())
        {
            cout<<s.top();
            s.pop();
            if(s.size()!=0)
            cout<<" ";
        }
        return 0;
    }
    //  输出结果:
    > cd "f:VScoding" ; if ($?) { g++ Yqifei.cpp -o Yqifei } ; if ($?) { .Yqifei }
    qiuqiu @ you meet to nice
    
原文地址:https://www.cnblogs.com/Yqifei/p/12660171.html