The queue achieves max operations, and the efficiency should be improved as much as possible.

Source: Internet
Author: User

Combine the previously implemented maxstack and use two stacks to implement one queue to implement maxqueue

 

import java.util.Stack;public class MaxQueue {    MaxStack in = new MaxStack();    MaxStack out = new MaxStack();    public void enqueue(Integer a) {        in.push(a);    }    public Integer dequeue() {        shiftItems();        return out.pop();    }    public Integer peek() {        shiftItems();        return out.peek();    }    public Integer max() {        return Math.max(in.isEmpty() ? Integer.MIN_VALUE : in.max(), out.isEmpty() ? Integer.MIN_VALUE : out.max());    }    private void shiftItems() {        if (!out.isEmpty())            return;        while (!in.isEmpty()) {            out.push(in.pop());        }    }    public static void main(String[] args) {        MaxQueue queue = new MaxQueue();        queue.enqueue(1);        System.out.println(queue.max());        queue.enqueue(2);        System.out.println(queue.max());        queue.enqueue(3);        System.out.println(queue.max());        queue.enqueue(4);        System.out.println(queue.max());        queue.dequeue();        System.out.println(queue.max());        queue.dequeue();        System.out.println(queue.max());        queue.dequeue();        System.out.println(queue.max());    }}class MaxStack {    Stack<Integer> val = new Stack<Integer>();    Stack<Integer> max = new Stack<Integer>();    public boolean isEmpty() {        return val.isEmpty();    }    public void push(Integer a) {        val.push(a);        if (max.isEmpty() || a >= max.peek())            max.push(a);    }    public Integer pop() {        Integer out = val.pop();        if (out == max.peek())            max.pop();        return out;    }    public Integer peek() {        return val.peek();    }    public Integer max() {        return max.peek();    }}

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.