zoukankan      html  css  js  c++  java
  • 栈的顺序存储实现

    #include<stdio.h>
    #include<stdlib.h>

    #define OK 1
    #define ERROR 0
    #define OVERFLOW -2
    #define TRUE 1
    #define FALSE 0
    #define INIT_SIZE 20
    #define INCREMENT_SIZE 10
    typedef int Elemtype;
    typedef int Status;

    typedef struct {
    Elemtype *base;//栈尾指针
    Elemtype *top;//栈顶指针
    int size;
    }SqStack;
    Status InitStack(SqStack *S)
    {
    S->base = (Elemtype *)malloc(INIT_SIZE*sizeof(Elemtype));
    if(!S->base)
    {
    exit(OVERFLOW);
    }
    S->top=S->base;
    S->size=INIT_SIZE;
    return OK;
    }

    Status Push(SqStack *S,Elemtype e)
    {
    if((S->top-S->base)/sizeof(Elemtype)>=S->size)
    {
    S->base=(Elemtype *)realloc(S->base,(S->size+INCREMENT_SIZE)*sizeof(Elemtype));
    if(!S->base)
    {
    exit(OVERFLOW);
    }
    S->top=S->base+S->size*sizeof(Elemtype);
    S->size+=INCREMENT_SIZE;
    }
    *S->top=e;
    S->top+=sizeof(Elemtype);
    return OK;

    }

    Status Pop(SqStack *S,Elemtype *e)
    {
    if(S->top==S->base)
    {
    printf("The stack is empty ");
    return ERROR;
    }
    else
    {
    S->top-=sizeof(Elemtype);
    *e=*S->top;
    return OK;
    }
    }
    Status TraverseStack(SqStack *S)
    {
    while(S->top>S->base)
    {
    printf("%d ",*S->base);
    S->base+=sizeof(Elemtype);
    }
    return OK;
    }
    int main()
    {
    int i;
    int a;
    SqStack S;
    int ret=InitStack(&S);
    if(ret)
    {
    printf("init_success ");
    }
    else
    {

    printf("init_error ");
    }
    for(i=0;i<10;i++)
    {
    Push(&S,i+1);

    }

    TraverseStack(&S);

    return 0;
    }

  • 相关阅读:
    Hibernate配置文件详解
    Struts工作原理、流程
    java三大框架原理
    JAVA三大框架的各自作用
    tomcat的种种
    jdk及tomcat的配置
    java-io-file
    JAVA-IO-文件过滤
    SPSS-单因素方差分析(ANOVA) 案例解析(转)
    SPSS-比较均值-独立样本T检验 案例解析(转)
  • 原文地址:https://www.cnblogs.com/loveyan/p/4556536.html
Copyright © 2011-2022 走看看