Simulate a Queue by opening two stack helpers, which transfer elements, and a Queue, which stores elements in reverse order. When pop(), the first element in the queue is queued.

Here’s an example: We start with four elements: 1, 2, 3, and 4, and since we only have stacks, we want to Queue them in the order of 4, 3, 2, and 1(from the bottom of the stack to the top of the stack), so we have a helper, so we put all the elements in the helper, In the helper, the elements from the bottom of the stack to the top are 1, 2, 3, and 4, so we can’t simulate Queue exit, so we push the top elements off the stack one by one, and the Queue is 4, 3, 2, and 1 (from the bottom of the stack to the top of the stack). All we need to do is pop().

And they’re saying that when we deleteHead, if the Queue is empty and return -1, we just need to check if the stack Queue is empty. Pop () if it is not empty.

In appendTail, note that the Queue may not be empty, so you need to eject all the elements of the Queue one by one into the helper before enqueuing.

For example, if the initial Queue is 1, 2, 3, 4, and the elements in the Queue are 4, 3, 2, 1 from the bottom of the stack to the top of the stack, and then the elements in the helper are 1, 2, 3, 4 from the bottom of the stack to the top of the stack, The next step is simply to eject all the elements in the helper and Queue them.

class CQueue {
stack<int> helper;
stack<int> Queue;
public:
    CQueueVoid appendTail(int value) {void appendTail(int value) {void appendTail(int value) {while(! Helper.empty ()) {// Empty the helper stack and move the Queue to helper.pop(); }while(! Queue.empty()) { int topElement = Queue.top(); helper.push(topElement); Queue.pop(); } helper.push(value);while(! helper.empty()) { int topElement = helper.top(); Queue.push(topElement); helper.pop(); } } intdeleteHead() {
        if(Queue.empty()) {
            return- 1; } int deletedElement = Queue.top(); Queue.pop();returndeletedElement; }};Copy the code