• C++顺序栈基本操作


      1 #include <iostream>
      2 #define STACKSIZE 50/*设栈中元素个数为50个*/
      3 using namespace std;
      4 
      5 struct SeqStack
      6 {
      7     int elem[STACKSIZE];
      8     int top;
      9 };
     10 
     11 /*构造一个空栈*/
     12 void InitStack(SeqStack *S)
     13 {
     14     S->top=-1;
     15 }
     16 
     17 /*将x置入S栈新栈顶*/
     18 bool Push(SeqStack *S,int x)
     19 {
     20     if(S->top==STACKSIZE-1)
     21         return false;
     22     S->top++;
     23     S->elem[S->top]=x;
     24     return true;
     25 }
     26 
     27 /*将S栈顶元素弹出,放到x所指的存储空间中带出*/
     28 bool Pop(SeqStack * S,int &x)
     29 {
     30     if(S->top==-1)
     31         return false;
     32     x = S->elem[S->top];
     33     S->top--;
     34     return true;
     35 }
     36 
     37 /*将栈S栈顶元素读出,放到x所指的存储空间中,栈顶指针保持不变*/
     38 bool GetTop(SeqStack * S, int &x)
     39 {
     40     if(S->top==-1)
     41         return false;
     42     x = S->elem[S->top];
     43     return true;
     44 }
     45 
     46 /*将栈清空*/
     47 void ClearStack(SeqStack * S)
     48 {
     49     S->top=-1;
     50 }
     51 
     52 /*判断栈S是否为空*/
     53 bool IsEmpty(SeqStack * S)
     54 {
     55     if(S->top==-1)
     56         return true;
     57     return false;
     58 }
     59 
     60 /*判断栈S是否已满*/
     61 bool IsFull(SeqStack * S)
     62 {
     63     if(S->top==STACKSIZE-1)
     64         return true;
     65     return
     66         false;
     67 }
     68 
     69 /*打印栈S所有元素*/
     70 void PrintStack(SeqStack S)
     71 {
     72     for(int i=0;i<=S.top;i++)
     73         cout << S.elem[i] << " ";
     74     cout << endl;
     75 }
     76 
     77 int main(){
     78     SeqStack s;
     79     InitStack(&s);
     80 
     81     for(int i=0;i<60;i++)
     82         Push(&s,i);
     83 
     84     cout << IsFull(&s) << endl;
     85 
     86     PrintStack(s);
     87     
     88     int x=0;
     89     
     90     Pop(&s,x);
     91     cout << "x= " << x << endl;
     92     PrintStack(s);
     93     Pop(&s,x);
     94     cout << "x= " << x << endl;
     95     PrintStack(s);
     96     Pop(&s,x);
     97     cout << "x= " << x << endl;
     98     PrintStack(s);
     99     Pop(&s,x);
    100     cout << "x= " << x << endl;
    101     PrintStack(s);
    102 
    103     GetTop(&s,x);
    104     cout << "x= " << x << endl;
    105     PrintStack(s);
    106     
    107     ClearStack(&s);
    108     PrintStack(s);
    109     cout << IsEmpty(&s) << endl;
    110     return 0;
    111 }
  • 相关阅读:
    关于php,python,javascript文件或者模块导入引入的区别和联系
    es6在网页中模块引入的方法
    pip3 升级失败的解决方法!亲测有效
    php 简单的学习GD库绘制图片并传回给前端实现方式
    session与cookie的区别以及HTML5中WebStorage理解
    二次开发项目集合
    php微信公众号开发入门小教程
    安装运行mariadb时错误:gtid_slave_pos
    发测试 HTML/FILE/MYSQL/动态 20151120
    百度浏览器 自动弹窗!
  • 原文地址:https://www.cnblogs.com/xxdfly/p/4378913.html
Copyright © 2020-2023  润新知