栈模拟队列 | 队列模拟栈 (JAVA)

栈模拟队列

思路:两个栈操作
从一个栈中push 从另外一个栈中pop

import java.util.Stack;

/**
 * @author yinglala
 * 栈模拟队列
 * 思路:两个栈操作
 * 从一个栈中push 从另外一个栈中pop
 */
public class Stack2Queue {
    private Stack stack1 = new Stack();
    private Stack stack2 = new Stack();

    //synchronized保证线程同步安全
    public synchronized void put(Object o){
        stack1.push(o);
    }

    public synchronized Object pop(){
        if(stack2.isEmpty() && stack1.isEmpty()){
            return null;
        }
        if(stack2.isEmpty()){
            while (!stack1.isEmpty()){
                stack2.push(stack1.pop());
            }
        }

        return stack2.pop();
    }

    public static void main(String[] args) {

        Stack2Queue s2q = new Stack2Queue();

        s2q.put(1);//第一元素
        s2q.put(2);//第二元素
        s2q.put(3);//第三元素

        System.out.println("栈模拟队列后head的数据"+s2q.pop());
        System.out.println("栈模拟队列后第二个数据"+s2q.pop());
        System.out.println("栈模拟队列后第三个数据"+s2q.pop());
    }

}

队列模拟栈

思路:用两个队列 queue1 queue2
* push:往一个队列queue1中add
* pop:也在同一个队列queue1中remove最后一条数据,其他的要放在queue2中暂存,当queue1中没有数据把queue2的数据放回来

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

/**
 * @author yinglala
 * 队列模拟栈
 * 思路:用两个队列 queue1 queue2
 * push:往一个队列queue1中add
 * pop:也在同一个队列queue1中remove最后一条数据,其他的要放在queue2中暂存,当queue1中没有数据把queue2的数据放回来
 */
public class Queue2Stack {

    private Queue queue1 = new LinkedList();
    private Queue queue2 = new LinkedList();

    public synchronized void push(Object o){
        queue1.add(o);
    }

    public synchronized Object pop(){
        if(queue1.isEmpty() && queue2.isEmpty()){
            return null;
        }
        if(queue1.isEmpty()){
            while (!queue2.isEmpty()){
                queue1.add(queue2.remove());
            }
        }

        while (queue1.size()>1){
             queue2.add(queue1.remove());
        }

        return queue1.remove();
    }

    public static void main(String[] args) {

        Queue2Stack q2s = new Queue2Stack();

        q2s.push(1);//第一元素
        q2s.push(2);//第二元素
        q2s.push(3);//第三元素

        System.out.println("栈模拟队列后head的数据"+q2s.pop());
        System.out.println("栈模拟队列后第二个数据"+q2s.pop());
        System.out.println("栈模拟队列后第三个数据"+q2s.pop());
        System.out.println("栈模拟队列后第四个数据"+q2s.pop());
    }


}

参考链接:https://www.cnblogs.com/qichunlin/p/9590332.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值