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;
    }

  • 相关阅读:
    设计模式(一)基础面向对象
    面试题之三门问题
    「巫师3(The Witcher 3:Wild Hunt)」游戏测评
    欧拉角和四元数
    struts标签遍历各种list Map
    浅谈HtmlCleaner+XPath解析html或者xml
    hadoop简单例子
    解决JSP参数传递乱码的问题
    Set、List、Map的区别(浅谈)
    做个犀利的码农
  • 原文地址:https://www.cnblogs.com/loveyan/p/4556536.html
Copyright © 2011-2022 走看看