zoukankan      html  css  js  c++  java
  • C语言顺序栈实现

    /*数序栈*/
    #include<stdio.h>
    #include<stdlib.h>
    #include<math.h>
    #define SElemType char
    #define STACK_INIT_SIZE   100
    #define STACK_INCREMENT 10
    #define OK 1
    #define ERROR -1
    #define Status int
    #define OVER -1
    /*栈空 top == base
    **栈满 top-base = stacksize
    **
    */
    typedef  struct
    {
        SElemType *base;
        SElemType *top;
        int stacksize;
        int length;
    }SqStack;
    /*数序栈结构*/
    
    /*栈的初始化*/
    Status  initSqStack(SqStack *s)
    {
        s->base = (SElemType*)malloc(STACK_INIT_SIZE * sizeof(SElemType));
        if(! s->base) return OVER;
        s->top = s->base;
        s->stacksize = STACK_INIT_SIZE;
        s->length = 0;
        return OK;
    }
    Status pushSqStack(SqStack *s,const SElemType item)
    {
        /* stack full*/
        if(s->top - s->base == STACK_INIT_SIZE)
        {
            s->base = (SElemType*)realloc(s->base,(STACK_INCREMENT+STACK_INIT_SIZE)*sizeof(SElemType));
            if(!s->base) return OVER;
            s->top = s->base+ s->stacksize;
            s->stacksize += STACK_INCREMENT;
        }
        *s->top++ = item;
    
        return OK;
    }
    
    Status popSqStack(SqStack *s,SElemType *item)
    {
        if(s->top == s->base) return ERROR;
        *item = *--(s->top);
        return OK;
    }
    /*获取栈长度*/
    int lengthSqStack(SqStack *s)
    {
        return s->top-s->base;
    }
    
    int main(void)
    {
        SElemType data;
        SqStack s;
        int len,i,sum =0;
        printf("Please input a binary digit
    ");
        initSqStack(&s);
        scanf("%c",&data);
        while(data !='#')
        {
            pushSqStack(&s,data);
            scanf("%c",&data);
        }
        getchar();
        len = lengthSqStack(&s);
        for(i = 0;i<len;i++)
        {
            popSqStack(&s,&data);
            printf("%c",data);
            sum += (data-48)*pow(2,i);
        }
        printf("Decimal is :%d.
    ",sum);
        getchar();
    
        return 0;
    }
  • 相关阅读:
    2-3-4 tree留坑
    CCPC final Cockroaches
    对拍模板
    使用cronolog按日期分割日志
    linux git 命了
    变量加减乘除运算
    根据pom标签修改
    根据符号获取字符
    shell循环字符串数组
    git ssh key配置
  • 原文地址:https://www.cnblogs.com/plxx/p/3489187.html
Copyright © 2011-2022 走看看