1. 程式人生 > >棧的基本操作

棧的基本操作

eal main int pre 初始化 typedef hello alloc 操作

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

棧的基本操作