用队列实现栈,用栈实现队列

用两个栈实现队列:
思想:比如 栈stack1,栈stack2,
向stack1中push元素:1、2、3、4、5、6
将stack1中的元素都出栈pop,然后push进stack2中:6、5、4、3、2、1;
这样stack1中无元素,stack2中元素:6、5、4、3、2、1,
然后出栈的时候从stack2中出,1就会先出栈;这样就实现了先进先出的效果;

import java.util.Stack;

/*
* 用两个栈实现一个队列
* */
public class QueueByStack {
    Stack stack1=new Stack<>();
    Stack stack2=new Stack<>();

    public void add(Integer num){
        stack1.push(num);
    }
    public Integer poll(){

        /*当第二个栈stack2是空时,将栈stack1中的元素全部出栈放到stack2中,此时最先进入到栈stack1中的元素就会被放到最顶端,就会在stack2中先出栈*/
        if (stack2.isEmpty()){
            while (!stack1.isEmpty()) {

                stack2.push(stack1.pop());
            }
        }
        return stack2.pop();
    }
    public Integer size(){
        return stack1.size()+stack2.size();
    }

    public Integer peek(){

        /*栈stack2中的栈顶元素就是最先进入栈stack1中的元素*/
        if (stack2.isEmpty()){
            while (!stack1.isEmpty()) {

                stack2.push(stack1.pop());
            }

        }
        return stack2.peek();
    }
    public static void main(String[] args) {

        QueueByStack queue=new QueueByStack();
        queue.add(1);
        queue.add(2);
        queue.add(3);
        queue.add(4);
        queue.add(5);

        System.out.println("出队列:"+queue.poll());
        System.out.println("出队列:"+queue.poll());
        System.out.println("出队列:"+queue.poll());
        
        queue.add(6);
        queue.add(7);
        System.out.println("队列长度"+queue.size());
        System.out.println("队列顶部元素:"+queue.peek());

        System.out.println("出队列:"+queue.poll());
        System.out.println("出队列:"+queue.poll());
        System.out.println("出队列:"+queue.poll());



    }
}

结果:
用队列实现栈,用栈实现队列_第1张图片
用一个队列实现栈:
思想:队列queue1;
向队列中add元素:1、2、3、4、5、6
要想实现先进后出的效果,就将1、2、3、4、5(除了最后一个元素),这前面的元素都先出(poll)队列,然后再add进队列;
队列中元素就变成了6、5、4、3、2、1;这样子出元素时,就是6先出(最后进入的先出),实现了队列的效果;
每一次出队列的时候都这样进行;

import java.util.LinkedList;
import java.util.Queue;

/*
* 用队列实现栈
*
* */
public class StackByQueue {

    Queue queue=new LinkedList<>();
    public void push(Integer num){
              queue.add(num);
    }

    public Integer pop(){


        /*将队列前面的元素(除了最后一个元素)都先出队列,再进队列,这样最后一个元素就变成了队列中的首位,这样子,最后一个进队列的就会先出队列*/
       for(int i=0;i

结果:
用队列实现栈,用栈实现队列_第2张图片

你可能感兴趣的:(用队列实现栈,用栈实现队列)