3.模拟栈

3.模拟栈

 3.模拟栈

 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 }

 

原文链接: https://www.cnblogs.com/fx1998/p/13284866.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍;

也有高质量的技术群,里面有嵌入式、搜广推等BAT大佬

    3.模拟栈

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/364943

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年3月2日 下午3:50
下一篇 2023年3月2日 下午3:50

相关推荐