栈和队列的“转换”

今天在复习数据结构时候,看到栈和队列这一章,有两个很有意思的问题,
1 如何使用两个栈来实现一个队列
2 如何使用两个队列来实现一个栈
思想都比较简单,简而言之就是两边儿来回倒
附两张图即可说明
两个栈实现一个队列

两个队列实现一个栈

接下来 记录一下这两个功能的java代码实现
首先是两个栈 实现一个队列

package learnstack;
import java.util.Stack;

/*
 * 本程序计划使用两个栈来实现一个队列 栈 先进后出   队列先进先出 怎么结合两个栈呢? 压进去弹到另一个栈中就好 
 */

public class test {

    Stack<Integer> stack1=new Stack <Integer>();
    Stack<Integer> stack2=new Stack <Integer>();

    public void push(int node){
        stack1.push(node);
    }


    public int pop(){
        if(stack2.size()<=0){
            while(stack1.size()>0){
                stack2.push(stack1.pop());  
            }           
        }

        if(stack2.isEmpty()){
            try{
                throw new Exception("queue is empty");
            }catch (Exception e){

            }
        }

        int head =stack2.pop();
        return head;
    }

    public static void main(String[] args){

        test test1=new test();

        test1.push(0);
        test1.push(1);
        test1.push(2);
        System.out.println(test1.pop());
        System.out.println(test1.pop());
        System.out.println(test1.pop());
    }

}

在程序中压入0 1 2 输出结果自然是0 1 2咯

接着来记录一下两个队列实现一个栈

package learnstack;
import java.util.Queue;
import java.util.ArrayDeque;
/*
 * 本程序使用两个队列实现一个栈 队列先进先出 栈后进先出  左右队列来回倒
 */


public class test2 {

    Queue<Integer> queue1= new ArrayDeque<>();
    Queue<Integer> queue2= new ArrayDeque<>();

public void push(int node){

    if(queue1.isEmpty()&&queue2.isEmpty()){
        queue1.add(node);
        return;
    }

    if(queue1.isEmpty()){
        queue2.add(node);
        return;
    }

    if(queue2.isEmpty()){
        queue1.add(node);
        return;
    }
}

public int pop(){

     if (queue1.isEmpty()&&queue2.isEmpty()) {
         try {
             throw new Exception("stack is empty");
         } catch (Exception e) {
         }
     }

     if(queue1.isEmpty()){
         while(queue2.size()>1){
             queue1.add(queue2.poll());
         }
         return queue2.poll();   
     }



    if(queue2.isEmpty()){
        while(queue1.size()>1){
            queue2.add(queue1.poll());
        }
        return queue1.poll();
    }

    return (Integer)null;
}
    public static void main(String[] args){

        test2 t2=new test2();
        t2.push(1);
        t2.push(2);
        t2.push(3);
        t2.push(4);
        System.out.println(t2.pop());
        System.out.println(t2.pop());


    }

}

压入的参数是1 2 3 4 显示两个结果 则 输出结果为 4 3 后进先出嘛!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值