stack栈的常见用法详解

1.stack的定义。

stack是一种先进后出的容器,要使用stack,应该先添加头文件#include,并在头文件限免加上using namespace std;

​ 其定义的写法和其他STL容器一样,typename可以是任何基本数据类型或容器

stack< typename > name;

2.stack容器内元素的访问

由于stack是一种先进后出的数据结构,在STL中的stack中只能通过top()来访问栈顶元素

#include <stdio.h>
#include<stack>
using namespace std;
int main(void)
{
    stack< int > st;
    for (int i = 0; i <5; i++) {
        st.push(i);
    }
    printf("%d",st.top());
    return 0;
}

3.stack常用函数实例解析

1.push()将x入栈,时间复杂度为O(1)

2.top()访问栈顶元素,时间复杂度为O(1)

3.pop()用以弹出栈顶元素,时间复杂度为O(1)

示例:

#include<stdio.h>
#include <stack>
using namespace std;
int main(void)
{
    stack< int > st;
    for(int i = 0; i < 5 ; i++)
    {
        st.push(i);
    }
    for (int i = 0; i <3 ; ++i) {
        st.pop();//连续三次将栈顶元素出栈,
    }
    printf("%d",st.top());
    return 0;
}

4.empty()可以检测stack内是否为空,返回true为空,返回false为非空,时间复杂度为O(1).

示例如下:

#include <stdio.h>
#include <stack>
using namespace std;
int main(void)
{
    stack< int > st;
    if(st.empty() == true)
    {
        printf("empty");
    }else
    {
        printf("not empty");
    }
    st.push(1);
    if(st.empty() == false)
    {
        printf("not empty");
    }else
    {
        printf("empty");
    }
    return 0;
}

4.size()返回stack的元素个数,时间复杂度为O(1)

#include <stdio.h>
#include <stack>
using namespace std;
int main(void)
{
    stack< int > st;
    for (int i = 0; i <5 ; ++i) {
        st.push(i);
    }
    printf("%d",st.size());
    return 0;
}

4.Stack的常见用途

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

猜你喜欢

转载自blog.csdn.net/J_aSON_/article/details/107929244