题目链接:232. 用栈实现队列 - 力扣(Leetcode)
还是老套路二话不说,先上代码
typedef char STDataType; typedef struct Stack { STDataType* a; int top; int capacity; }ST; // 初始化栈 void STInit(ST* pst); // 销毁栈 void STDestroy(ST* pst); // 添加数据 void STPush(ST* pst, STDataType x); // 删除数据 void STPop(ST* pst); // 弹出数据 STDataType STTop(ST* pst); // 判断是否为空 bool STEmpty(ST* pst); // 判断大小 int STSize(ST* pst); // 初始化栈 void STInit(ST* pst) { assert(pst); pst->a = NULL; pst->top = 0; pst->capacity = 0; } // 销毁栈 void STDestroy(ST* pst) { assert(pst); free(pst->a); pst->a = NULL; pst->top = 0; pst->capacity = 0; } // 添加数据 void STPush(ST* pst, STDataType x) { if (pst->capacity == pst->top) { int newcapacity = (pst->capacity == 0 ? 4 : pst->capacity * 2); STDataType* tmp = (STDataType*)realloc(pst->a, newcapacity * sizeof(STDataType)); if (tmp == NULL) { perror("realloc fail"); return; } pst->a = tmp; pst->capacity = newcapacity; } pst->a[pst->top] = x; pst->top++; } // 删除数据 void STPop(ST* pst) { assert(pst); assert(!(STEmpty(pst))); pst->top--; } // 弹出数据 STDataType STTop(ST* pst) { assert(pst); assert(!(STEmpty(pst))); return pst->a[pst->top - 1]; } // 判断是否为空 bool STEmpty(ST* pst) { assert(pst); return pst->top == 0; } // 判断大小 int STSize(ST* pst) { assert(pst); return pst->top; } typedef struct { ST pushst; ST popst; } MyQueue; MyQueue* myQueueCreate() { MyQueue* obj = (MyQueue*)malloc(sizeof(MyQueue)); if(obj==NULL) { perror("malloc fail"); return NULL; } STInit(&(obj->pushst)); STInit(&(obj->popst)); return obj; } void myQueuePush(MyQueue* obj, int x) { assert(obj); STPush(&(obj->pushst), x); } int myQueuePop(MyQueue* obj) { assert(obj); if(!STEmpty(&(obj->popst))) { int tem = STTop(&(obj->popst)); STPop(&(obj->popst)); return tem; } while(!STEmpty(&(obj->pushst))) { STPush(&(obj->popst), STTop(&(obj->pushst))); STPop(&(obj->pushst)); } int tem = STTop(&(obj->popst)); STPop(&(obj->popst)); return tem; } int myQueuePeek(MyQueue* obj) { assert(obj); if(STEmpty(&(obj->popst))) { while(!STEmpty(&(obj->pushst))) { STPush(&(obj->popst), STTop(&(obj->pushst))); STPop(&(obj->pushst)); } } int tem = STTop(&(obj->popst)); return tem; } bool myQueueEmpty(MyQueue* obj) { return (STEmpty(&(obj->pushst)) && STEmpty(&(obj->popst))); } void myQueueFree(MyQueue* obj) { STDestroy(&(obj->popst)); STDestroy(&(obj->pushst)); free(obj); obj = NULL; } /** * Your MyQueue struct will be instantiated and called as such: * MyQueue* obj = myQueueCreate(); * myQueuePush(obj, x); * int param_2 = myQueuePop(obj); * int param_3 = myQueuePeek(obj); * bool param_4 = myQueueEmpty(obj); * myQueueFree(obj); */
过啦!!!!!!
解题思路:
此题可以用两个栈实现,一个栈进行入队操作,另一个栈进行出队操作 出队操作: 当出队的栈不为空是,直接进行出栈操作,如果为空,需要把入队的栈元素全部导入到出队的栈,然后再进行出栈操作