• 3.模拟栈


     

     

    用c++里的stack容器很容易做出来

     1 #include <bits/stdc++.h>
     2 using namespace std;
     3 int main() {
     4     stack<int> s;
     5     int n;
     6     cin >> n;
     7     while (n--) {
     8         string op;
     9         int x;
    10         cin >> op;
    11         if (op == "push") {
    12             cin >> x;
    13             s.push(x);
    14         } else if (op == "pop") {
    15             s.pop();
    16         } else if (op == "empty") {
    17             if (s.empty()) {
    18                 cout << "YES" << endl;
    19             } else {
    20                 cout << "NO" << endl;
    21             }
    22         } else if (op == "query") {
    23             cout << s.top() << endl;
    24         }
    25     }
    26     return 0;
    27 }

    现在考察用数组手动实现一个栈

     1 #include <bits/stdc++.h>
     2 using namespace std;
     3 const int N = 100010;
     4 int stk[N], tt;
     5 int main() {
     6     int m;
     7     cin >> m;
     8     while (m--) {
     9         string s;
    10         int x;
    11         cin >> s;
    12         if (s == "push") {
    13             cin >> x;
    14             stk[++tt] = x;
    15         } else if (s == "pop") {
    16             tt--;
    17         } else if (s == "empty") {
    18             if (tt > 0) {
    19                 cout << "NO" << endl;
    20             } else {
    21                 cout << "YES" << endl;
    22             }
    23         } else if (s == "query") {
    24             cout << stk[tt] << endl;
    25         }
    26     }
    27     return 0;
    28 }
  • 相关阅读:
    angular4浏览器兼容问题
    angular4组件生命周期
    angular4路由
    CDH 安装配置指南(Tarball方式)
    nginx-1.14.0安装
    redis-3.0.6安装
    CDH安装kafka
    CDH配置JAVA_HOME
    ntp集群时间同步
    VMware联网
  • 原文地址:https://www.cnblogs.com/fx1998/p/13284866.html
Copyright © 2020-2023  润新知