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

    入栈,出栈,取栈顶元素,遍历

      1 #include<stdio.h>
      2 #include<string.h>
      3 #include<queue>
      4 #include<stack>
      5 
      6 #define stacksize 100
      7 #define ERROR 0
      8 #define OK 1
      9 #define OVERFLOW -1
     10 
     11 typedef int Status;
     12 typedef int ElemType;
     13 
     14 typedef struct
     15 {
     16     ElemType data[stacksize];
     17     int top;
     18 }SeqStack;
     19 
     20 void InitStack(SeqStack &s)//初始化
     21 {
     22     s.top=0;
     23 }
     24 
     25 int StackEmpty(SeqStack s)//判断栈空
     26 {
     27     return (s.top==0);
     28 }
     29 
     30 int StackFull(SeqStack s)//判断栈满
     31 {
     32     return (s.top==stacksize);
     33 }
     34 
     35 Status Push(SeqStack &s,ElemType x)//入栈
     36 {
     37     if(StackFull(s))
     38     {
     39         printf("栈已满!");
     40         return 0;
     41     }
     42     s.data[s.top++]=x;
     43     return 1;
     44 }
     45 
     46 Status Pop(SeqStack &s,ElemType &x)//出栈
     47 {
     48     if(StackEmpty(s))
     49     {
     50         printf("栈空!");
     51         return 0;
     52     }
     53     x=s.data[--s.top];
     54     return  1;
     55 }
     56 
     57 Status GetTop(SeqStack s,ElemType &x)//取栈顶元素
     58 {
     59     if(StackEmpty(s))
     60     {
     61         printf("栈空!");
     62         return 0;
     63     }
     64     x=s.data[s.top-1];
     65     return 1;
     66 }
     67 
     68 void StackTravels(SeqStack &s)//栈遍历
     69 {
     70     int i;
     71     for(i=0;i<s.top;i++)
     72         printf("%d  ",s.data[i]);
     73 }
     74 
     75 int main()
     76 {
     77     int i,n,d;
     78     SeqStack s1;
     79     InitStack(s1);
     80     printf("请输入n:");
     81     scanf("%d", &n);
     82     printf("请输入%d个数:", n);
     83     for(i=0;i<n;i++)
     84     {
     85         scanf("%d", &d);
     86         Push(s1,d);
     87     }
     88     printf("栈中的数据是:");
     89     StackTravels(s1);
     90     printf("
    ");
     91     GetTop(s1,d);
     92     printf("栈顶元素是%d
    ", d);
     93 
     94     printf("执行一次逆序输出。");
     95     while(!StackEmpty(s1))
     96     {
     97         Pop(s1,d);
     98         printf("%d ", d);
     99     }
    100 
    101     printf("
    ");
    102 
    103     /*printf("执行一次出栈操作。
    ");
    104     Pop(s1,d);
    105     printf("出栈元素是%d
    ", d);
    106     printf("栈中数据是:
    ");
    107     StackTravels(s1);
    108     printf("
    ");*/
    109 }
  • 相关阅读:
    python基础—函数装饰器
    python基础—函数嵌套与闭包
    Python之三级菜单
    Python之运算符
    Python之字典
    Python之购物车
    Python之列表
    Python之布尔
    Python之“Hello World”
    Python之递归函数
  • 原文地址:https://www.cnblogs.com/weiyuan/p/5947061.html
Copyright © 2011-2022 走看看