Aunt Guan is participating in the “Java Theme month – Java brush question clocking”, see the activity link for more details

First of all, I want to clarify that every algorithm problem has multiple solutions, and we’ll just talk about a few excellent solutions in LeetCode ~, hopefully

Can help you, that we first look at the topic description ~

I. Title Description:

Use queues to implement the following operations on the stack:

Push (x) -- element x pushes pop() -- removes the top element top() -- retrieves the top element empty() -- returns whether the stack is emptyCopy the code

Note: You can only use the basic operations on queues — push to back, peek/pop from front, size, and is empty are legal. Your language may not support queues. You can use a list or a deque to simulate a queue, as long as it’s standard queue operations. You can assume that all operations are valid (for example, no pop or top operations are called on an empty stack).

Ii. Analysis of Ideas:

The stack is a fifo data structure, and the queue is a fifO data structure. In order to implement fifO, we can put the first element in the queue after the first element. In addition, the queue also has the operation of fetching and deleting the first element, so we should focus on how to put the first element after the element when adding. Let’s look at the implementation:

Third, code demonstration

class MyStack { Queue<Integer> queue; public MyStack() { queue = new LinkedList<Integer>(); Public void push(int x) {int n = queue.size(); // Add a new element queue.offer(x); For (int I =0; int I =0; int I =0; i<n; i++){ queue.offer(queue.poll()); Public int pop() {return queue.poll(); Public int top() {return queue.peek(); } public Boolean empty() {return queue.isempty (); }}Copy the code

Brush question summary

If you have other ideas to solve the problem, as long as you can achieve the requirements, it is no problem, all roads lead to Rome, not just limited to the solution I said ha ~, excellent ideas and code is more learning significance, let’s work together