【吐出无顺序,打印的时候需要连续】

数据结构设计

消息流不断地吐出1~N的序号及其信息,但不一定按顺序,但是打印的时候需要连续,设计接收并打印的结构

public static class Node{
        public String info;
        public Node next;
        public Node(String str){
            info=str;
        }
    }
    public static class MessageBox{
        private HashMap<Integer,Node> headMap;
        private HashMap<Integer,Node> tailMap;
        private int waitPoint;
        public MessageBox(){
            headMap=new HashMap<Integer,Node>();
            tailMap=new HashMap<Integer, Node>();
            waitPoint=1;
        }
        public void receive(int num,String info){
            if(num<1){
                return;
            }
            Node cur=new Node(info);
            headMap.put(num,cur);
            tailMap.put(num,cur);
            if(tailMap.containsKey(num-1)){
                tailMap.get(num-1).next=cur;
                tailMap.remove(num-1);
                headMap.remove(num);
            }
            if(headMap.containsKey(num+1)){
                cur.next=headMap.get(num+1);
                tailMap.remove(num);
                headMap.remove(num+1);
            }
            if(num==waitPoint){
                print();
            }
        }
        public void print(){
            Node node=headMap.get(waitPoint);
            headMap.remove(waitPoint);
            while (node!=null){
                System.out.print(node.info+" ");
                node=node.next;
                waitPoint++;
            }
            tailMap.remove(waitPoint-1);
            System.out.println();
        }
    }
    public static void main(String[] args) {
        // MessageBox only receive 1~N
        MessageBox box = new MessageBox();
        // 1....
        System.out.println("这是2来到的时候");
        box.receive(2,"B"); // - 2"
        System.out.println("这是1来到的时候");
        box.receive(1,"A"); // 1 2 -> print, trigger is 1
        box.receive(4,"D"); // - 4
        box.receive(5,"E"); // - 4 5
        box.receive(7,"G"); // - 4 5 - 7
        box.receive(8,"H"); // - 4 5 - 7 8
        box.receive(6,"F"); // - 4 5 6 7 8
        box.receive(3,"C"); // 3 4 5 6 7 8 -> print, trigger is 3
        box.receive(9,"I"); // 9 -> print, trigger is 9
        box.receive(10,"J"); // 10 -> print, trigger is 10
        box.receive(12,"L"); // - 12
        box.receive(13,"M"); // - 12 13
        box.receive(11,"K"); // 11 12 13 -> print, trigger is 11

    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值