一种消息接收并打印的结构设计

链接
已知一个消息流会不断地吐出整数1∼N,但不一定按照顺序吐出。如果上次打印的数为i,那么当i+1出现时,请打印i+1及其之后接收过的并且连续的所有数,直到1∼N全部接收并打印完,请设计这种接收并打印的结构

import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        while (in.hasNext()) {
            int n = in.nextInt();
            MessageBox messageBox = new MessageBox();
            while (n-- > 0) {
                messageBox.receive(in.nextInt());
            }
        }
    }
}

class MessageBox {

    private int wait;

    private Map<Integer, Node> headMap;

    private Map<Integer, Node> tailMap;

    private Map<Integer, Node> nodeMap;

    public MessageBox() {
        this.wait = 1;
        this.headMap = new HashMap<>();
        this.tailMap = new HashMap<>();
        this.nodeMap = new HashMap<>();
    }


    private Node addNode(int value) {
        Node node = new Node(null, value);
        headMap.put(value, node);
        tailMap.put(value, node);
        nodeMap.put(value, node);
        return node;
    }

    public void receive(int value) {

        Node newNode = addNode(value);

        if (tailMap.containsKey(value - 1)) {
            tailMap.get(value - 1).next = newNode;
            tailMap.remove(value - 1);
            headMap.remove(value);
        }

        if (headMap.containsKey(value + 1)) {
            newNode.next = headMap.get(value + 1);
            tailMap.remove(value);
            headMap.remove(value + 1);
        }

        tryPrint(value);
    }

    private void remove(int value) {
        headMap.remove(value);
        tailMap.remove(value);
        nodeMap.remove(value);
    }

    private void tryPrint(int value) {
        if (this.wait == value) {
            int nextWait = this.wait;
            Node node = nodeMap.get(value);
            while (node != null) {
                System.out.println(node.value + " " + this.wait);
                nextWait++;
                remove(node.value);
                node = node.next;
            }
            this.wait = nextWait;
        }
    }


    class Node {
        Node next;
        int value;

        public Node(Node next, int value) {
            this.next = next;
            this.value = value;
        }
    }
}
上一篇:图书馆管理系统(IO流)


下一篇:朴素贝叶斯