首页 > 代码库 > 栈的基本操作

栈的基本操作

#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;
}

 

栈的基本操作