• 数据结构--栈


    一个栈

    //
    #include <stdio.h>
    #include <math.h>
    #include <stdlib.h>
    #include <algorithm>
    #define STACK_INIT_SIZE  20
    #define STACK_INCREMENT  10
    
    typedef char ElemType;
    typedef struct
    {
        ElemType *base;
        ElemType *top;
        int stacksize;
    }sqStack;
    
    void initStack(sqStack *s)
    {
        //内存中开辟一段连续空间作为栈空间,首地址赋值给 s->base 
        s->base = (ElemType *)malloc(STACK_INIT_SIZE * sizeof(ElemType));
        if (!s->base) exit(0);   //分配空间失败
        s->top = s->base;  //最开始,栈顶就是栈底
        s->stacksize = STACK_INIT_SIZE;
    }
    
    void Push(sqStack* s, ElemType e)
    {
        /////栈满,追加空间
        if (s->top - s->base >= s->stacksize)
        {
            s->base = (ElemType *)realloc(s->base, (s->stacksize + STACK_INCREMENT)*sizeof(ElemType));
    
            if (!s->base)
            {
                exit(0); //内存分配失败
            }
            s->top = s->base + s->stacksize;
            s->stacksize = s->stacksize + STACK_INCREMENT;//设置栈的最大容量
        }
        *(s->top) = e; //放入数据 
        s->top++;
    }
    
    void Pop(sqStack *s, ElemType *e)
    {
        if (s->top == s->base)
        {
            return;
        }
        *e = *--(s->top);
    }
    
    int StackLen(sqStack s)
    {
        return (s.top - s.base);
    }
    
    void DestoryStack(sqStack* s)
    {
        free(s->base);  //释放内存空间
        s->base = s->top = nullptr;//栈底栈顶指针置为nullptr 
        s->stacksize = 0;//设置栈的最大容量为0
    }
    
    void main()
    {
        printf("Hello world!
    ");
    
        ElemType c;
        sqStack s;
        int len, i, sum = 0;
    
        printf("Please input a Binary digit.
    ");
    
        initStack(&s);//创建一个栈来存放二进制字符串
        ///输入 0/1 字符表示的二进制数,以#结束
        scanf("%c", &c);
        while (c != '#')
        {
            Push(&s, c);
            scanf("%c", &c);
        }
        getchar();
        len = StackLen(s);
    
        for (i = 0; i < len; i++)
        {
            Pop(&s, &c);
            sum = sum + (c - 48)*pow(2, i);  //转为十进制
        }
        printf("Decimal is %d.
    ", sum);
        DestoryStack(&s);
    
        getchar();
    }
    
    ///input:   10010101#
    ///output:  149 
  • 相关阅读:
    Python编程题24--回文数
    Python编程题23--移动零
    Python编程题22--只出现一次的数字
    Python编程题21--每日温度
    Python编程题20--最大子序和
    Python编程题19--比特位计数
    推荐系统中对比实验工具--伯乐bole
    pytorch中反向传播的loss.backward(retain_graph=True)报错
    win10彻底禁止自动更新(家庭版操作)
    linux使用清华源安装工具,切换清华源
  • 原文地址:https://www.cnblogs.com/music-liang/p/12628972.html
Copyright © 2020-2023  润新知