栈的简单实现

    xiaoxiao2021-03-25  108

    栈的简单实现 #include #include #include #define max_stack_length 20 #define append_stack_length 5 using namespace std; typedef struct { int *base; int *top; int stackSize; }SqStack; ///初始化栈 int InitStack(SqStack& S) { S.base = (int*) malloc(max_stack_length * sizeof(int)); if(!S.base) return -1; S.top = S.base; S.stackSize = max_stack_length; return 0; } ///获取栈的头元素 int GetTop(SqStack& S, int &e) { if(S.base == S.top) return -1; e = *(S.top-1); return 0; } ///push int Push(SqStack& S, int value) { if(S.top-S.base>=S.stackSize) { S.base = (int *)realloc(S.base,(S.stackSize + append_stack_length)); if(!S.base)return -1; S.top = S.base + S.stackSize; S.stackSize = S.stackSize + append_stack_length; } *S.top++ = value; return 0; } int Pop(SqStack& S, int& e) { if(S.base == S.top) return -1; e = *--S.top; return 0; } int main() { SqStack S; InitStack(S); for(int i = 0;i <23;i++) { Push(S,i); } int e; GetTop(S,e); printf("%d\n",e); for(int i = 0;i<23;i++) { Pop(S,e); printf("%d,",e); } return 0; }
    转载请注明原文地址: https://ju.6miu.com/read-7505.html

    最新回复(0)