栈的简单实现——使用C++容器库(STL Stack)

来源:互联网 发布:淘宝卖家登陆中心 编辑:程序博客网 时间:2024/06/05 18:50

前言

作为比较简单的数据结构,使用C++容器库中的栈(std::stack)也相对比较简单。
在头文件中,栈的定义为:

template<    class T,    class Container = std::deque<T>> class stack;

Stack

常用函数:

  • top():访问栈顶
  • empty():判断栈空
  • size():返回栈中元素数
  • push():向栈顶插入元素
  • pop():删除栈顶元素

代码

#include <iostream>#include <stdio.h>#include <stdlib.h>#include <string>#include <stack>using namespace std;int main(){  int n;  while (cin>>n) {    stack<int> s;    string ch;    int val;    while (n--) {      cin>>ch;      if (ch == "PUSH") {        cin>>val;        s.push(val);      } else if (ch == "POP") {        if (!s.empty())          s.pop();      } else if (ch == "TOP") {        if (!s.empty())          cout<<"Top : "<<s.top()<<endl;        else          cout<<"Empty"<<endl;      }      cout<<"Size : "<<s.size()<<endl;    }    cout<<endl;  }}

测试结果

Stack

参考资料

http://zh.cppreference.com/w/cpp/container/stack

0 0
原创粉丝点击