队列实现栈,栈实现队列

1. 用队列实现栈结构

  • 图的深度优先遍历需要用栈来实现。
  • 用队列实现图的深度优先遍历方法是:先用队列实现栈结构,再用栈结构实现图的深度优先遍历。
  • 代码思路:构建两个队列:Data队列和help队列;压入数据时数据都进Data队列,假设队列中按顺序进入了1,2,3,4,5,返回数据时,把1,2,3,4 放入help队列,然后拿出Data中的5返回;接着改引用,将Data队列和help队列的引用交换;下次返回数据时就依然是把Data队列中的123放入help队列,然后拿出Data队列中的4返回,再交换两队列的引用,如此反复。
public class StackAndQueueConvert {
    //队列实现栈
    public class TwoQueues_Stack {
        Queue<Integer> queue = new LinkedList<>();
        Queue<Integer> helper = new LinkedList<>();

        public void push(int pushInt) {
            queue.add(pushInt);
        }

        public int pop() {
            if (queue.isEmpty()) {
                throw new RuntimeException("Stack is empty!");
            }
            while (queue.size() != 1) {
                helper.add(queue.poll());
            }
            int res = queue.poll();
            swap();
            return res;
        }

        public int peek() {
            if (queue.isEmpty()) {
                throw new RuntimeException("Stack is empty!");
            }
            while (queue.size() != 1) {
                helper.add(queue.poll());
            }
            int res = queue.poll();
            helper.add(res);
            swap();
            return res;
        }

        public void swap() {
            Queue<Integer> temp = helper;
            helper = queue;
            queue = temp;
        }
    }
}

2. 栈实现队列

  • 思路:构建两个栈:Push栈和Pop栈;将Push栈中的数据倒入Pop栈中然后返回给用户,就实现了队列。需要注意两个条件:①Pop栈为空时才能其中倒入数据。②向Pop栈倒入数据时必须要倒完。
  • 固定栈1入队,栈2出队。pop() 操作时,①如果两栈都为空,报异常;②如果出队栈有元素就出队;③如果出队栈为空,就把入队栈的元素都弹过来再出队。
public class StackAndQueueConvert {
    //栈实现队列
    public class TwoStacks_Queue {
        Stack<Integer> stackPush = new Stack<>();
        Stack<Integer> stackPop = new Stack<>();

        public void push(int p) {
            stackPush.push(p);
        }

        public int poll() {
            if (stackPush.isEmpty() && stackPop.isEmpty()) {
                throw new RuntimeException("Queue is empty!");
            } else if (stackPop.isEmpty()) {
                while (!stackPush.isEmpty()) {
                    stackPop.push(stackPush.pop());
                }
            }
            return stackPop.pop();
        }

        public int peek() {
            if (stackPush.isEmpty() && stackPop.isEmpty()) {
                throw new RuntimeException("Queue is empty!");
            } else if (stackPop.isEmpty()) {
                while (!stackPush.isEmpty()) {
                    stackPop.push(stackPush.pop());
                }
            }
            return stackPop.peek();
        }
    }
}
发布了307 篇原创文章 · 获赞 11 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/dl674756321/article/details/105226866