用栈实现队列

86 阅读1分钟

1. 用栈实现队列

力扣题目链接

public class MyQueue {
    Stack<Integer> in;
    Stack<Integer> out;

    public MyQueue() {
        in = new Stack<>();
        out = new Stack<>();
    }
//    把项压入堆栈顶部。
    public void push(int x) {
        in.push(x);
    }
//    移除堆栈顶部的对象,并作为此函数的值返回该对象。
    public int pop() {
        dumpstackIn();
        return out.pop();
    }
//    查看堆栈顶部的对象,但不从堆栈中移除它。
    public int peek(){
        dumpstackIn();
        return out.peek();
    }

    public boolean empty(){
        dumpstackIn();
        return out.isEmpty();
    }
    // 将in中的数全部压入out中
    private void dumpstackIn(){
        if (out.isEmpty()) {
            while (!in.isEmpty()) {
                out.push(in.pop());
            }
        }
    }
}

2. 用队列实现栈

力扣题目链接

public class MyStack {
    Queue<Integer> queue;

    public MyStack() {
        queue = new LinkedList<>();
    }

    //    把项压入堆栈顶部。
    public void push(int x) {
        //队列中每放入一个数,就将这个数置于队列首部
        queue.offer(x);
        theLastElementToTheFront();
    }

    //    移除堆栈顶部的对象,并作为此函数的值返回该对象。
    public int pop() {
        return queue.poll();
    }

    //    查看堆栈顶部的对象,但不从堆栈中移除它。
    public int top() {
        return queue.peek();
    }

    public boolean empty() {
        return queue.isEmpty();
    }
//    让最后一个元素到队列最前面
    public void theLastElementToTheFront() {
        for (int i = 0; i < queue.size() - 1; i++) {
            queue.offer(queue.poll());
        }
    }
}