In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-23 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
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!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.