The JAVA implementation uses two stacks to implement a queue, completes the queue's push and the pop operation ("The sword refers to the offer") __java

Source: Internet
Author: User

Recently in the brush "sword refers to offer" in the programming problem, but the internet about "sword refers to offer" solution is mostly C or C + +, and the official (author) is also in C + + to explain, here himself with Java wrote some of the answer code of the topic (of course, there are also some of the answers to the online others, The source does not indicate please point out, the invasion of the deletion, hope to be able to help everyone's study.


Topic:

Implement a queue with two stacks to complete the push and pop operations of the queue. The elements in the queue are of type int.


In fact, is the queue normal into the stack, the stack when the contents of the stack in order to move to another stack, negative negative positive, so again in order out of the stack, became the stack before the order of the queue


Import Java.util.Stack; Use the stack remember to refer to the Java.util,stack package public
 
class Solution {
   stack<integer> stack1 = new stack<integer> ();
   stack<integer> Stack2 = new stack<integer> ();
   
into the stack function public
   void push (int num) {
       stack1.push (num);    What to push into the stack directly with the stack of the pushed method is good
   
//out of the stack function public
   int pop () {
   Integer re=null; 
       if (!stack2.empty ()) {  //if stack 2 is not empty, then take out the topmost one
           re=stack2.pop (); 
       } else{ 
               //If stack 2 is empty, take out the number of stacks 1, and put it in the stack 2 while
           (!stack1.empty ()) {   
                re=stack1.pop (); 
                Stack2.push (re); 
                  After a number in the Stack 2, again take the inside number out
                  if (!stack2.empty ()) { 
                         re=stack2.pop (); 
                   } 
       } 
       return re; 
    }
}





Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.