LeetCode | 232. 用栈实现队列
OJ链接
解题思路:
- 此题可以用两个栈实现,一个栈进行入队操作,另一个栈进行出队操作
- 出队操作: 当出队的栈不为空是,直接进行出栈操作,如果为空,需要把入队的栈元素全部导入到出队的栈,然后再进行出栈操作
- 入数据,往
pushST
入 - 出数据,看
popST
有没有数据,有的话直接出,如果popST
没有数据,把pushST
数据导入到popST
,然后再出数据
代码实现:
typedef struct {
//入队栈
Stack pushST;
//出队栈
Stack popST;
} MyQueue;
/** Initialize your data structure here. */
MyQueue* myQueueCreate(int maxSize) {
MyQueue* pqueue = (MyQueue*)malloc(sizeof(MyQueue));
StackInit(&pqueue->pushST, maxSize);
StackInit(&pqueue->popST, maxSize);
return pqueue;
}
/** Push element x to the back of queue. */
void myQueuePush(MyQueue* obj, int x) {
//入队栈进行入栈操作
StackPush(&obj->pushST, x);
}
/** Removes the element from in front of queue and returns that element. */
int myQueuePop(MyQueue* obj) {
//如果出队栈为空,导入入队栈的元素
if(StackEmpty(&obj->popST) == 0)
{
while(StackEmpty(&obj->pushST) != 0)
{
StackPush(&obj->popST, StackTop(&obj->pushST));
StackPop(&obj->pushST);
}
}
int front = StackTop(&obj->popST);
//出队栈进行出队操作
StackPop(&obj->popST);
return front;
}
/** Get the front element. */
int myQueuePeek(MyQueue* obj) {
//类似于出队操作
if(StackEmpty(&obj->popST) == 0)
{
while(StackEmpty(&obj->pushST) != 0)
{
StackPush(&obj->popST, StackTop(&obj->pushST));
StackPop(&obj->pushST);
}
}
return StackTop(&obj->popST);
}
/** Returns whether the queue is empty. */
bool myQueueEmpty(MyQueue* obj) {
return StackEmpty(&obj->pushST) == 0
&& StackEmpty(&obj->popST) == 0;
}
void myQueueFree(MyQueue* obj) {
StackDestroy(&obj->pushST);
StackDestroy(&obj->popST);
free(obj);
}