1 two-sided record
Because Xiaolan wanted to do a short video Internet company at the time, but there were few related companies in the school to recruit, so she trek to Huda, took the on-site written test that night, and received the next day's retest notice in the middle of the night. In the face, the interviewer asked the hand to tear the stack to implement the queue .
Here everyone can think for 1 minute
Review by the way
Stack and queue
It will be better if you look at the solution
Features of the stack
The stack is a first-in -last-out data structure . Elements in the stack are pushed from the top of the stack (top), and popped from the top of the stack (top). Note : We need to judge whether the stack is full for pushing , and whether the stack is empty for popping . Let's take a look at the picture to deepen the impression.
Stack 1 2 3
Pop 3 2 1
Characteristics of queue
Queue is a first-in first-out data structure . Elements in the queue enter the team (push) from the rear (rear), and exit (pop) from the head (front). Similarly, we use a graph to deepen the impression.
Enqueue 1 2 3
Dequeue 1 2 3
1Leetcode232 uses stack to implement queue
Use the stack to implement the following operations of the queue :
push(x) - Put an element at the end of the queue.
pop() - Remove elements from the head of the queue.
peek() - Returns the element at the head of the queue.
empty() - Returns whether the queue is empty.
Example:
MyQueue queue = new MyQueue();
queue.push(1);
queue.push(2);
queue.peek(); // returns 1
queue.pop(); // returns 1
queue.empty(); // return false
0 1 Question analysis
I believe you already know that the stack is first-in-last-out and the queue is first-in-first-out. Assuming that 123 into the stack, the stack is the first time 321 (Anti-once), but we want to order out for 123, then we are on this basis, then the anti-time.
Ok, in fact, we need to introduce another stack to help us complete, as shown below.
Well, here is a summary of the realization ideas and precautions:
With two stacks, the element first enters the A stack and then exits the B stack.
Attention should be paid to pop() and peek:
If there are elements on the B stack, pop them directly from the B stack.
If there is no element in the B stack, push the A stack element into the B stack.
Although the topic is simple, savor the truth carefully ! Must master it!
0 3 code implementation
1c++ version
2python version
3java version