/** Push element x to the back of queue. */ voidmyQueuePush(MyQueue* obj, int x) { //入数据就往pushST里面入 StackPush(&obj->pushST,x); }
/** Removes the element from in front of queue and returns that element. */ intmyQueuePop(MyQueue* obj) { //类似于下面的peek // if(StackEmpty(&obj->popST)) // { // while(!StackEmpty(&obj->pushST)) // { // StackPush(&obj->popST,StackTop(&obj->pushST)); // StackPop(&obj->pushST); // } // } // int top = StackTop(&obj->popST); /////////////////////////////////////////////////////////////// //或者直接调用下面的myQueuePeek函数直接获取popST的栈顶元素 //保存给top之后删除,然后return int top = myQueuePeek(obj); StackPop(&obj->popST); return top; }
/** Get the front element. */ intmyQueuePeek(MyQueue* obj) { //出数据要从popST里面出 //如果popST里面是空的 //就要先从pushST里面拿 if(StackEmpty(&obj->popST)) { //把pushST里面的元素导到popST里面 //然后取第一个 while(!StackEmpty(&obj->pushST)) { //取pushST最上面的元素依次压进popST StackPush((&obj->popST),StackTop(&obj->pushST)); StackPop(&obj->pushST); } } return StackTop(&obj->popST); }
/** Returns whether the queue is empty. */ boolmyQueueEmpty(MyQueue* obj) { return StackEmpty(&obj->popST) && StackEmpty(&obj->pushST); }
/** * 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); */