Implement a queue with two stacks

Ideas:

  Assuming that there are two stacks stack1 and stack2, it can be considered as follows:

    What is stored in stack2 is [the front part of the queue], which can be considered as the value of the top of the stack = the value of the head of the queue.

    The elements in stack1 are [untransformed rear elements of the queue], which are equivalent to the existence of buffers. It is actually the result of the reverse order of the rear elements in the queue. Therefore, all its elements need to be put into stack2 to complete the flipping process.

 

The drawing is as follows:

| <---- queue----> |
| <- stack 2 -> | <- stack 1 -> |
| Consistent with queue order | Contrary to queue order |

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325247852&siteId=291194637