算法笔记--标准模板库STL--stack

stack的常见用法

stack翻译为栈,是STL中实现的一个后进先出的容器

头文件

#include<stack>
using namespace std;

stack的定义

stack<typename> name;

stack容器内元素的访问

只能通过top()来访问栈顶元素

#include<iostream>
#include<stack>
using namespace std;

int main(){
    stack<int> st;
    for(int i = 1; i <= 5; i++)
        st.push(i);

    printf("%d", st.top());	// 5

    return 0;
}

stack常用函数

push( )

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

top( )

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

pop( )

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

#include<iostream>
#include<stack>
using namespace std;

int main(){
    stack<int> st;
    for(int i = 1; i <= 5; i++)
        st.push(i);

    for(int i = 1; i <= 3; i++)
        st.pop();               // 出栈3次

    printf("%d", st.top());     // 2

    return 0;
}

empty( )

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

size( )

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

#include<iostream>
#include<stack>
using namespace std;

int main(){
    stack<int> st;
    for(int i = 1; i <= 5; i++)
        st.push(i);

    for(int i = 1; i <= 3; i++)
        st.pop();               // 出栈3次

    st.empty() ? printf("Empty\n") : printf("No Empty\n");

    printf("%d\n", st.size());
    printf("%d", st.top());

    return 0;
}
No Empty
2
2

stack的常见用途

  • 用来模拟实现一些递归,防止程序对栈内存的限制而导致程序运行错误

Write by Gqq

猜你喜欢

转载自www.cnblogs.com/zgqcn/p/12588428.html