数据结构与算法(Java) 20:栈和队列相互实现

题目 如何仅用队列结构实现栈结构? 如何仅用栈结构实现队列结构?

1. 用队列实现栈:

思路 设置两个队列queue1和queue2实现(共有N个数):

① push操作相同;

② pop操作时,将queue1中前N-1个数push进queue2中,返回剩余的最后一个值;queue2与queue1交换一下,即可完成。

③ peek操作类似与pop操作,只不过是需要将最后一个值也push进queue2中后,再交换。

package algorithm.section3;

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

public class QueueToStack {
    private Queue<Integer> queue1;
    private Queue<Integer> queue2;

    public QueueToStack(){
        queue1 = new LinkedList<Integer>();
        queue2 = new LinkedList<Integer>();
    }

    public void push(int obj){
        queue1.add(obj);
    }

    public Integer pop(){
        if (queue1.isEmpty()) throw new IndexOutOfBoundsException("The Stack is Empty!");
        while (queue1.size() > 1) queue2.add(queue1.poll());
        Integer flag = queue1.poll();
        swap();
        return flag;
    }

    public Integer peek(){
        if (queue1.isEmpty()) throw new IndexOutOfBoundsException("The Stack is Empty!");
        while (queue1.size() > 1) queue2.add(queue1.poll());
        Integer flag = queue1.poll();
        queue2.add(flag);
        swap();
        return flag;

    }

    public void swap(){
        Queue<Integer> f = queue1;
        queue1 = queue2;
        queue2 = f;
    }
}

 2. 用栈实现队列:

思路 设置两个栈stack1和stack2实现(共有N个数):

① push操作相同;

② poll操作时,先判断stack2是否为空,若为空,则将stack1中的全部元素push进stack2中,然后弹出stack2中的栈顶元素;若非空,则不做任何操作,直接弹出stack2中的栈顶元素。

③ peek操作直接返回stack2的栈顶元素。

package algorithm.section3;

import java.util.Stack;

public class StackToQueue {
    private Stack<Integer> stack1;
    private Stack<Integer> stack2;

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

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

    public Integer poll(){
        if (stack1.isEmpty() && stack2.isEmpty()) throw new IndexOutOfBoundsException("The queue is empty!");
        pull();
        return stack2.pop();
    }

    public Integer peek(){
        if (stack1.isEmpty() && stack2.isEmpty()) throw new IndexOutOfBoundsException("The queue is empty!");
        pull();
        return stack2.peek();
    }

    public void pull(){
        if (!stack2.isEmpty()) return;
        while (!stack1.isEmpty())
            stack2.push(stack1.pop());
    }
}
发布了149 篇原创文章 · 获赞 36 · 访问量 4万+

猜你喜欢

转载自blog.csdn.net/Dorothy_Xue/article/details/105590798