题目描述(题目来源:力扣)
思路:
typedef struct {
Stack pushST;
Stack popST;
} MyQueue;
/** Initialize your data structure here. */
MyQueue* myQueueCreate() {
MyQueue*q =(MyQueue*) malloc(sizeof(MyQueue));
StackInit(&q->popST);
StackInit(&q->pushST);
return q;
}
/** 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))
{
while(!StackEmpty(&obj->pushST));
{
StackPush(&obj->popST,StackTop(&obj->pushST));
StackPop(&obj->pushST);
}
}*/
int top = myQueuePeek(&obj->popST);
StackPop(&obj->popST);
return top;
}
/** Get the front element. */
int myQueuePeek(MyQueue* obj) {
if(StackEmpty(&obj->popST))
{
while(!StackEmpty(&obj->pushST));
{
StackPush(&obj->popST,StackTop(&obj->pushST));
StackPop(&obj->pushST);
}
}
return StackPop(&obj->popST);
}
/** Returns whether the queue is empty. */
bool myQueueEmpty(MyQueue* obj) {
StackEmpty(&obj->pushST)&&StackEmpty(&obj->popST);
}
void myQueueFree(MyQueue* obj) {
StackDestory(&obj->pushST);
StackDestory(&obj->popST);
free(obj);
}
cs