栈(stack)

来源:互联网 发布:c语言字符比大小 编辑:程序博客网 时间:2024/06/08 11:43

引言


栈是一种常用的数据结构,栈中的元素是先进后出,栈只有一个出口,只允许对栈顶进行操作。


基本用法


头文件:#include<stack>

创建一个栈:stack<int> s

压栈:s.push(x)

出栈:s.pop()

返回栈顶元素:s.top()

返回栈中元素数目:s.size()

堆栈为空则返回真:s.empty()


实战


#include<iostream>#include<stack>using namespace std;int main(){    stack<int> s;//定义一个栈    s.push(1);//压栈    s.push(2);    s.push(3);    s.pop();//出栈    cout<<s.top()<<endl;//返回栈顶元素    cout<<s.size()<<endl;//返回栈中元素数目    cout<<s.empty()<<endl;//堆栈为空则返回真    return 0;}



练习场


http://acm.nyist.net/JudgeOnline/problem.php?pid=2


原创粉丝点击