• OOP栈类模板(模板+DS)


    目录

    题目描述

    AC代码


    题目描述

    借助函数模板实现栈的操作。

    栈是一种先进后出的数据结构,它的插入、删除只能在栈顶位置进行。Push为入栈操作,即插入,Pop为出栈操作,即删除。

    栈的操作类似叠盘子,先放的盘子在底下,后放的盘子上面。当要取盘子,就从最上面取。

    例如入栈数据1到2再到3,那么3在最上面,1在最下面。当要出栈数据,就是3先出,接着是2,最后是1出栈。

    要求你自行定义栈结构,并利用函数模板以及类模板完成对char,int和float型数据的处理。其中,我们定义:

    输入

    第一行为测试数据数

    对于每组测试数据,第一行为数据类型,第二行为操作数

    对于每次操作均进行Push或Pop操作。要注意,当空栈弾栈时要给出Error提示

    输出

    对于每次入栈,不需输出。对于每次出栈,输出出栈元素或给出Error提示。当完成所有操作后,依次逆序输出栈中剩余元素

    输入样例1

    3
    I
    6
    Push 6
    Push 1
    Push 1
    Pop
    Pop
    Pop
    C
    4
    Pop
    Push a
    Push a
    Pop
    F
    8
    Push 4.1
    Push 4.2
    Push 14.1
    Push 4.2
    Push 1314
    Push 1314
    Pop
    Pop

    输出样例1

    1 is popped from stack!
    1 is popped from stack!
    6 is popped from stack!
    Empty Stack!
    Error!
    a is popped from stack!

    1314 is popped from stack!
    1314 is popped from stack!
    4.2 14.1 4.2 4.1 

    AC代码

    1. #include<iostream>
    2. #include<string>
    3. #include<algorithm>
    4. #include<cmath>
    5. #include<iomanip>
    6. using namespace std;
    7. template<class kind>
    8. class stack {
    9. kind p[10000];
    10. int top = -1;
    11. public:
    12. void push() {
    13. kind num;
    14. cin >> num;
    15. p[++top] = num;
    16. }
    17. void pop() {
    18. if (empty()) {
    19. cout << "Error!" << endl;
    20. } else {
    21. cout << p[top--] << " is popped from stack!" << endl;
    22. }
    23. }
    24. bool empty() {
    25. if (top < 0)
    26. return 1;
    27. return 0;
    28. }
    29. void display() {
    30. if (empty())
    31. cout << "Empty Stack!" << endl;
    32. else {
    33. for (int i = top;i>=0;i--)
    34. cout << p[i] << ' ';
    35. cout << endl;
    36. }
    37. }
    38. };
    39. int main() {
    40. int test, count;
    41. char code;
    42. string index;
    43. cin >> test;
    44. while (test--) {
    45. cin >> code >> count;
    46. if (code == 'I') {
    47. stack<int> temp;
    48. while (count--) {
    49. cin >> index;
    50. if (index == "Push")
    51. temp.push();
    52. else
    53. temp.pop();
    54. }
    55. temp.display();
    56. } else if (code == 'C') {
    57. stack<char> temp;
    58. while (count--) {
    59. cin >> index;
    60. if (index == "Push")
    61. temp.push();
    62. else
    63. temp.pop();
    64. }
    65. temp.display();
    66. } else {
    67. stack<float> temp;
    68. while (count--) {
    69. cin >> index;
    70. if (index == "Push")
    71. temp.push();
    72. else
    73. temp.pop();
    74. }
    75. temp.display();
    76. }
    77. }
    78. }
  • 相关阅读:
    ChatGPT提示词Prompts
    冷知识:unity使用的是左手坐标系
    淘宝天猫京东商品详情一键铺货到拼多多平台店铺接口代码对接教程
    数据结构·顺序表
    阿里面试:我们为什么要分库分表
    业务系统高可用性建设
    公有云攻击案例
    Row 28 was cut by GROUP_CONCAT()
    Spring Cloud面试题整理
    数仓中的数据对象及相关关系的解读
  • 原文地址:https://blog.csdn.net/weixin_62264287/article/details/125453388