Java通过两个栈构造队列,通过两个队列构造栈(剑指offer面试题9)

通过两个栈构造队列
import java.util.Stack;

/**
 * @program: javaStudyTest
 * @description: 通过两个栈构造队列
 * @create: 2020-03-06
 **/
public class QueueBy2Stacks<T> {
    private Stack<T> stack1;
    private Stack<T> stack2;

    public QueueBy2Stacks() {
        stack1 = new Stack<>();
        stack2 = new Stack<>();
    }


    public void offer(T t) {
        stack1.push(t);
    }

    public T poll() {
        if (stack2.empty()) {
            while (!stack1.empty()) {
                stack2.push(stack1.pop());
            }
        }
        return stack2.empty() ? null : stack2.pop();
    }


    public static void main(String[] args) {
        QueueBy2Stacks<String> queueBy2Stacks = new QueueBy2Stacks<>();
        queueBy2Stacks.offer("qqqqqqqqq");
        queueBy2Stacks.offer("wwwwwww");
        queueBy2Stacks.offer("eeeeee");
        queueBy2Stacks.offer("ttttttt");

        System.out.println(queueBy2Stacks.poll());
        System.out.println(queueBy2Stacks.poll());
        System.out.println(queueBy2Stacks.poll());
        System.out.println(queueBy2Stacks.poll());
        System.out.println(queueBy2Stacks.poll());

    }

}

通过两个队列构造栈
import java.util.LinkedList;
import java.util.Queue;

/**
 * @program: javaStudyTest
 * @description:
 * @create: 2020-03-07
 **/
public class StackBy2Queue<T> {
    private Queue<T> queue1;
    private Queue<T> queue2;

    public StackBy2Queue() {
        queue1 = new LinkedList<T>();
        queue2 = new LinkedList<T>();
    }

    public void push(T t) {
        if (queue1.isEmpty()) {
            queue2.offer(t);
        } else {
            queue1.offer(t);
        }
    }

    public T pop() {
        if (queue1.isEmpty() && queue2.isEmpty()) {
            return null;
        }
        if (queue1.isEmpty()) {
            while (queue2.size() > 1) {
                queue1.offer(queue2.poll());
            }
            return queue2.poll();
        } else {
            while (queue1.size() > 1) {
                queue2.offer(queue1.poll());
            }
            return queue1.poll();
        }
    }


    public static void main(String[] args) {
        StackBy2Queue<String> stackBy2Queue = new StackBy2Queue<>();

        stackBy2Queue.push("1111111111111");
        stackBy2Queue.push("2222222222222");
        stackBy2Queue.push("3333333333333");
        stackBy2Queue.push("4444444444444");

        System.out.println(stackBy2Queue.pop());
        System.out.println(stackBy2Queue.pop());
        System.out.println(stackBy2Queue.pop());
        System.out.println(stackBy2Queue.pop());
        System.out.println(stackBy2Queue.pop());
        System.out.println(stackBy2Queue.pop());
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值