《剑指offer-P6》【剑指Offer 09.用两个栈实现队列】
    
 
 
文章目录
 
 
 
💎一、题目
 
🏆1.题目描述
 
 
🏆2.原题链接
 
 
💎二、解题报告
 
🏆1.思路分析
 
 
🏆2.代码详解
 
typedef int STDataType;
typedef struct Stack{
    STDataType* a;
    int top;
    int capicity;
}ST;
void StackInit(ST* ps){
    assert(ps);
    ps->top = ps->capicity = 0;
    ps->a = NULL;
}
void Stackdestroy(ST* ps){
    assert(ps);
    free(ps->a);
    ps->a = NULL;
    ps->top = ps->capicity = 0;
}
void StackPush(ST* ps, STDataType x){
    if(ps->top == ps->capicity){
        int newcapicity = ps->capicity == 0 ? 4 : ps->capicity * 2;
        STDataType* tmp = (STDataType*)realloc(ps->a, sizeof(STDataType) * newcapicity);
        if(tmp == NULL){
            return exit(-1);
        }
        ps->a = tmp;
        ps->capicity = newcapicity;
    }
    ps->a[ps->top++] = x;
}
void StackPop(ST* ps){
    assert(ps);
    if(ps->top == 0){
        return ;
    }
    ps->top--;
}
bool StackEmpty(ST* ps){
    assert(ps);
    return ps->top == 0;
}
STDataType StackTop(ST* ps){
    assert(ps);
    if(StackEmpty(ps)){
        return -1;
    }
    return ps->a[ps->top-1];
}
typedef struct {
    ST pop;
    ST push;
} CQueue;
CQueue* cQueueCreate() {
    CQueue* obj = (CQueue*)malloc(sizeof(CQueue));
    StackInit(&obj->pop);
    StackInit(&obj->push);
    return obj;
}
void cQueueAppendTail(CQueue* obj, int value) {
    assert(obj);
    StackPush(&obj->push, value);
}
int cQueueDeleteHead(CQueue* obj) {
    assert(obj);
    int ret = -1;
    if(StackEmpty(&obj->pop)){
        while(!StackEmpty(&obj->push)){
            StackPush(&obj->pop, StackTop(&obj->push));
            StackPop(&obj->push);
        }
        ret = StackTop(&obj->pop);
        StackPop(&obj->pop);
    }else{
        ret = StackTop(&obj->pop);
        StackPop(&obj->pop);
    }
    return ret;
}
void cQueueFree(CQueue* obj) {
    assert(obj);
    Stackdestroy(&obj->pop);
    Stackdestroy(&obj->push);
    free(obj);
}