数据结构--栈

一个栈

 

//
#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!\r\n");

    ElemType c;
    sqStack s;
    int len, i, sum = 0;

    printf("Please input a Binary digit.\r\n");

    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.\r\n", sum);
    DestoryStack(&s);

    getchar();
}

///input:   10010101#
///output:  149 

 

posted @ 2020-04-03 21:08  He_LiangLiang  阅读(185)  评论(0编辑  收藏  举报