typedef struct {
int stackInTop, stackOutTop;
int stackIn[100], stackOut[100];
} MyQueue;
MyQueue* myQueueCreate() {
MyQueue* queue = (MyQueue*)malloc(sizeof(MyQueue));
queue->stackInTop = 0;
queue->stackOutTop = 0;
return queue;
}
void myQueuePush(MyQueue* obj, int x) {
obj->stackIn[(obj->stackInTop)++] = x;
}
int myQueuePop(MyQueue* obj) {
int stackInTop = obj->stackInTop;
int stackOutTop = obj->stackOutTop;
if (stackOutTop == 0)
{
while (stackInTop > 0)
{
obj->stackOut[stackOutTop++] = obj->stackIn[--stackInTop];
}
}
int top = obj->stackOut[--stackOutTop];
while (stackOutTop > 0)
{
obj->stackIn[stackInTop++] = obj->stackOut[--stackOutTop];
}
obj->stackInTop = stackInTop;
obj->stackOutTop = stackOutTop;
return top;
}
int myQueuePeek(MyQueue* obj) {
return obj->stackIn[0];
}
bool myQueueEmpty(MyQueue* obj) {
return obj->stackInTop == 0 && obj->stackOutTop == 0;
}
void myQueueFree(MyQueue* obj) {
obj->stackInTop = 0;
obj->stackOutTop = 0;
}
// 注意 --stackOutTop
代码随想录算法训练营第十天| LeetCode 232.用栈实现队列 225. 用队列实现栈
于 2023-09-16 14:59:22 首次发布