How does Java implement queues with two stacks
This article mainly explains "how to realize the queue with two stacks in Java". Interested friends may wish to take a look. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn "how Java implements queues with two stacks".
Answer to the question
Description
The characteristic of the stack is first-in-first-out, and the characteristic of the queue is first-in-first-out. When the numbers enter stack 1 in turn, exit stack 1 in turn and press into stack 2 in turn, and then exit the stack in the same order as entering stack 1.
Therefore, entering the queue is achieved by pressing into stack 1, and the pop-up queue is achieved by popping up the stack top elements of stack 2. When popping up elements, you need to ensure that the order of the current stack pop-up elements is the same as that of the queue pop-up elements, that is, all the elements of stack 1 should be pushed into stack 2.
Code
Import java.util.Stack;public class Solution {Stack stack1 = new Stack (); Stack stack2 = new Stack (); public void push (int node) {/ / directly into the stack1 stack stack1.push (node);} public int pop () {/ / if stack2 is empty if (stack2.isEmpty ()) {while (! stack1.isEmpty ()) {stack2.push (stack1.pop ());}} return stack2.pop () }} at this point, I believe you have a deeper understanding of "how Java uses two stacks to implement queues". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!