zoukankan      html  css  js  c++  java
  • 数据结构之线性结构栈

    栈是一种比较重要的线性结构,能够解决很多困难的问题,在此写个代码小小总结一下。

    这里采用的实现方式是顺序结构,链式结构有待完善。。。

    上代码:

     1 #include<iostream>
     2 using namespace std;
     3 
     4 class stack
     5 {
     6 private:
     7     int msize;
     8     int *st;
     9     int top;
    10 public:
    11     stack(int size);
    12     bool push(int &item);
    13     bool pop();
    14     void display();
    15     bool clear();
    16     ~stack();
    17 };
    18 
    19 stack::stack(int size)
    20 {
    21     msize = size;
    22     st = new int[msize];
    23     top = -1;
    24 }
    25 
    26 bool stack::push(int &item)
    27 {
    28 
    29     if(top == msize-1)
    30     {
    31         cout<< "栈已满!" << endl;
    32         return 0;
    33     }
    34     st[++top] = item;
    35     return 1;
    36 }
    37 
    38 bool stack::pop()
    39 {
    40     if(top == -1)
    41     {
    42         cout<< "栈已空!" << endl;
    43         return 0;
    44     }
    45     //item = st[top--];
    46     top--;
    47     return 1;
    48 }
    49 
    50 void stack::display()
    51 {
    52     int temp = top;
    53     while(temp != -1)
    54     {
    55         cout << st[temp] << " ";
    56         temp--;
    57     }
    58     
    59     cout<< endl;
    60 }
    61 bool stack::clear()
    62 {
    63     top = -1;
    64     return 1;
    65 }
    66 
    67 stack::~stack()
    68 {
    69     delete [] st;
    70 }
    71 
    72 int main()
    73 {
    74     stack st(10);
    75     int ele;
    76     cout<< "输入元素 :" << endl;
    77     for(int i=0;i<10;i++)
    78     {
    79         cin>>ele;
    80         st.push(ele);
    81     }
    82     cout<< " 所有元素出栈 :" << endl;
    83     st.display();
    84     st.pop();
    85     st.pop();
    86     cout<< "弹出两个元素之后打印 : " << endl;
    87     st.display();
    88     return 0;
    89 }

    程序运行结果:

    Fight fight fight ! 你有你的奇迹 ! Fight fight fight ! Just to be yourself !
  • 相关阅读:
    机器学习学习笔记之二:决策树
    机器学习学习笔记之一:K最近邻算法(KNN)
    Shell脚本编程中的几个问题
    Linux服务器配置git服务
    Ubuntu下安装IDA pro
    网络扫描(二)
    网络扫描(一)
    Docker学习过程中遇到的问题及解决方法
    CentOS7中升级Docker版本
    解决CentOS无法解析域名的问题
  • 原文地址:https://www.cnblogs.com/sjlove/p/3093780.html
Copyright © 2011-2022 走看看