9 offer a second forum prove safety questions: implementing stacks (JAVA Version) with two queues

Title: Stack implemented with two queues.

Analysis: for simulation analysis with a queue stack through a series of stack push and pop operations, as shown, to let a stack to push the element a. Since both queues are empty now, we can choose to either of the two insert a queue. We may wish to insert a queue1. Continue to the next stack to push b, c two elements. We put them all insert queue1. This time queue1 contains three elements a, b, c at the head of the queue where a, c located at the tail of the queue.

We now consider the Pops an element from the stack. According to the principle of LIFO stack, and finally was pushed onto the stack c should be the first to be ejected. Since the tail is located queue1 c, and we can only remove elements from the head of the queue, so we can sequentially remove a / b from and inserted into the queue queue2, and then remove the queue1 from c. This is equivalent to the pop elements from the stack c. We can use the same method from the pop-up element b in the stack.

Next, we consider a stack to push from the inner element d. At this time have a queue1 element, we put d queue1 inserted tail. If we pop an element from the stack, then the pop-up should be the last to be pushed d. Since d is located in the tail queue1, we can only start with the head and remove elements queue1 inserted into queue2, until the queue1 d encountered then directly delete it. as the picture shows:

code show as below:

public  class MyStack {
     Private Queue <Integer> Queue1;
     Private Queue <Integer> Queue2;
     public MyStack () { 
        Queue1 = new new the LinkedList <> (); 
        Queue2 = new new the LinkedList <> (); 
    } 
    
    // add, which queue is not empty is added to that queue 
    public  void Push (Integer NUM) {
         IF (queue1.size () == 0 && queue2.size () == 0 ) { 
            queue1.add (NUM); 
        } the else  IF (queue1.size () == 0 ) { 
            queue2.add (NUM);
        }else{
            queue1.add(num);
        }
    }
    
    //删除
    public Integer pop(){
        if(queue1.size() == 0 && queue2.size() == 0){
            return null;
        }
        int value=0;
        if(queue1.size()>0){
            while(queue1.size()>0){
                queue2.add(queue1.remove());
            }
            value=queue1.remove();
        }
        if(queue2.size()>0){
            while(queue2.size()>0){
                queue1.add(queue2.remove());
            }
            value=queue2.remove();
        }
        return value;
    }
}

 

Guess you like

Origin www.cnblogs.com/xhlwjy/p/11259319.html