两个队列实现栈、两个栈实现队列

一、两个队列实现栈

思路

由于栈是先进后出,而队列是先进先出,故我们可以将一个含n个元素的队列的前n-1个元素出队,并进入到第一个队列中,这时候第一个队列就只剩最后一个元素了,输出。这便是输出最后一个元素了。

示例代码
import java.util.LinkedList;
import java.util.Queue;

public class QueueStack {
    private static Queue<Integer> queue1 = new LinkedList<Integer>();
    private static Queue<Integer> queue2 = new LinkedList<Integer>();

    public static void main(String[] args) {
        push(1);
        push(2);
        System.out.println(pop());
        push(3);
        System.out.println(pop());
        System.out.println(pop());
    }

    public static void push(int item) {
        int size1 = queue1.size();
        if (size1 == 0) {
            queue2.offer(item);
        } else {
            queue1.offer(item);
        }
    }
    public static Integer pop() {
        int size1 = queue1.size();
        int size2 = queue2.size();
        if (size1 == 0 && size2 != 0) {// 元素全部在queue2
            for (int i = 0; i < size2 - 1; i++) {
                queue1.offer(queue2.poll());
            }
            return queue2.poll();
        } else if (size1 != 0 && size2 == 0) {// 全部都在queue1
            for (int i = 0; i < size1 - 1; i++) {
                queue2.offer(queue1.poll());
            }
            return queue1.poll();
        }
        return null;
    }

}

二、两个栈实现队列

思路

由于栈是先进后出,而队列是先进先出,这里存在着一个倒序,故我们将第一个栈的元素全部进入到第二个栈,相当于再次倒序,两次倒序等于正序了,便是先进先出了。

示例代码
import java.util.Stack;

public class StackQueue {
    private static Stack<Integer> stack1 = new Stack<Integer>();
    private static Stack<Integer> stack2 = new Stack<Integer>();

    public static void main(String[] args) {
        enQueue(1);

        System.out.println(deQueue());
        enQueue(3);
        enQueue(2);
        System.out.println(deQueue());

        System.out.println(deQueue());
    }

    public static void enQueue(Integer item) {
        stack1.push(item);
    }

    public static Integer deQueue() {
        if (!stack2.isEmpty()) {
            return stack2.pop();
        } else {
            if (!stack1.isEmpty()) {
                while (!stack1.isEmpty()) {
                    stack2.push(stack1.pop());
                }
                return stack2.pop();
            } else {
                return null;
            }
        }
    }
}

猜你喜欢

转载自blog.csdn.net/qq_35890572/article/details/83149875
今日推荐