码迷,mamicode.com
首页 > 其他好文 > 详细

数据结构--栈

时间:2020-04-03 22:00:38      阅读:64      评论:0      收藏:0      [点我收藏+]

标签:释放内存   容量   空间   please   oid   real   tor   push   realloc   

一个栈

 

//
#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 

 

数据结构--栈

标签:释放内存   容量   空间   please   oid   real   tor   push   realloc   

原文地址:https://www.cnblogs.com/music-liang/p/12628972.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!