用两个栈来实现一个队列,完成队列的offer和peek操作。

用两个栈来实现一个队列,完成队列的offer和peek操作。 假定队列中的元素为int类型。队列中的泛型无需实现,只实现offer和peek方法;

package test;

import java.util.Stack;

public class MyQueue {

    Stack<Integer> data = new Stack<Integer>();
    Stack<Integer> temp = new Stack<Integer>();
    
    public void offer(int d) {
        data.push(d);
        System.out.println("入栈:"+d);
    }
    public int peek() {
        temp.clear();
        int n = data.size();
        for(int i=0;i<n;i++) {
            temp.push(data.pop());
        }
        int d = temp.peek();
        for(int i=0;i<n;i++) {
            data.push(temp.pop());
        }
        return d;
    }
    
    public static void main(String[] args) {
        MyQueue queue = new MyQueue();
        queue.offer(1);
        queue.offer(2);
        queue.offer(3);
        queue.offer(4);
        System.out.println("peek:"+queue.peek());

    }

}

public class Test {
    static class MyQueue {
        Stack<Integer> in = new Stack<>();
        Stack<Integer> out = new Stack<>();

        public void offer(int val) {
            in.push(val);
        }

        public int peek() {
            checkOut();
            return out.isEmpty() ? -1 : out.peek();
        }

        public int poll() {
            checkOut();
            return out.isEmpty() ? -1 : out.pop();
        }

        private void checkOut() {
            if (!out.isEmpty()) {
                return;
            }
            while (!in.isEmpty()) {
                out.push(in.pop());
            }
        }
    }

    public static void main(String[] args) {
        MyQueue queue = new MyQueue();
        queue.offer(1);
        queue.offer(2);
        queue.offer(3);
        queue.offer(4);
        System.out.println(queue.peek());
        System.out.println(queue.peek());
        System.out.println(queue.poll());
        System.out.println(queue.poll());
        System.out.println(queue.peek());
        System.out.println(queue.poll());
        System.out.println(queue.poll());
        System.out.println(queue.poll());
        queue.offer(5);
        queue.offer(6);
        queue.offer(7);
        System.out.println(queue.poll());
        System.out.println(queue.peek());
    }
}

测试示例:

img