zoukankan      html  css  js  c++  java
  • c语言描述的顺序栈实现

    #include<stdio.h>
    #include<stdlib.h>
    #define initsize 100
    #define ok 1
    #define error 0
    typedef int Status;
    typedef char ElemType;
    typedef struct{
        ElemType *base;
        ElemType *top;
        int stacksize;
    }SqStack;
    static SqStack *S;
    Status InitStack(SqStack *S){
        S->base=(ElemType *)malloc(initsize*sizeof(ElemType));
        if(!S->base){
            printf("分配内存失败!");
            exit(error);
        }
        S=->top=S->base;
        S->stacksize=initsize;
        return ok;
    }
    Status StackEmpty(SqStack *S){
      if(S->base==S->top){
      return true;
      }else{
      return false;
    }
    }
    Status DestroyStack(SqStack
    *S){   free(S->base);
      return 0; } Status ClearStack(SqStack
    *S); Status StackEmpty(SqStack *S); Status StackLength(SqStack *S); Status GetTop(SqStack *S,ElemType e){ if(S->top!=S->base){ e=*(S->top-1);//非空栈的栈顶指针始终在栈顶元素的下一个位置 } return e; } Status Push(SqStack *S,ElemType e){ if(S->top-S->base>=initsize){ S->base=(ElemType *)realloc(S->base,(initsize+10)*sizeof(ElemType)) if(!S->base){ printf("内存分配失败"); exit(error); } S->stacksize+=10; S->top=S->base+S->stacksize;//此处的initsize为没有重新分派的initsize因为分配了空间不代表着top就要指向最顶 } *S->top++=e; return ok; } Status Pop(SqStack *S,ElemType *e){ if(S->top!=S->base){ S->top--; e=*S->top; return ok; }else{ return error; } } Status StackTraverse(const SqStack *S){ int *p; if(S->base==S->top){ exit(error); }else{ for(p=S->base;p<S->top;p++){ printf("%c ",*p); } } } void main(){ int m; InitStack(S); printf("请输入一个入栈元素 ",&m); Push(S,m); StackTraverse(S); }
  • 相关阅读:
    osg::BlendFunc来设置透明度
    LCA(Tarjan)
    CODEVS1073 家族 (并查集)
    CODEVS1533 互斥的数(哈希表)
    2014-12-4
    BZOJ2661 连连看 (费用流)
    2014-11-30
    JAVA语法基础作业——动手动脑以及课后实验性问题
    课后作业01——相加
    再读大道至简第二章
  • 原文地址:https://www.cnblogs.com/zzy-frisrtblog/p/5708039.html
Copyright © 2011-2022 走看看