首页 > 其他 > 详细

栈的基本操作

时间:2017-06-10 13:44:37      阅读:239      评论:0      收藏:0      [点我收藏+]
#include <stdio.h>
#include <stdlib.h>

#define STACK_INIT_SIZE 100
#define STACKINCREMENT 10


typedef struct{
    ElemType *base;
    ElemType *top;
    int stackSize;
}sqStack;


// 初始化栈
initStack(sqStack *s){
    s->base = (ElemType *)malloc(STACK_INIT_SIZE * sizeof(ElemType) );
    if( !s->base ) {
        exit(0);
    }
    s->top = s->base;  // 最开始栈顶就是栈底
    s->stackSize = STACK_INIT_SIZE;
}

// 入栈
Push(sqStack *s, ElemType e) {
    // 如果栈满追加空间
    if( s->top - s->base >= s->stackSize) {
        s->base = (ElemType *)realloc(s->base, (s->stackSize + STACKINCREMENT) * sizeof(ElemType));
        if ( !s->base ) {
            exit(0);
        }
        s->top = s->base + s->stackSize;
        s->stackSize = s->stackSize + STACKINCREMENT;
    }
    *(s->top) = e;
    s->top++;
}

// 出栈
Pop(sqStack *s,ElemType *e){
    if( s->top == s->base ) // 栈空
    {
        return;
    }
    *e = *--(s->top);
}
int main()
{
    printf("Hello world!\n");
    return 0;
}

 

栈的基本操作

原文:http://www.cnblogs.com/ncuhwxiong/p/6978308.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!