• 两个链表去重合并排序成一个链表


    方法一: 将两个链表放在同一个TreeSet中,然后遍历TreeSet,将TreeSet的值放入一个新链表中

        public Node megerLinkedFunc01(Node node1, Node node2) {
            Set<Integer> mergeSet = new TreeSet<Integer>();
            while (node1.next != null) {
                mergeSet.add(node1.value);
                node1 = node1.next;
            }
            while (node2.next != null) {
                mergeSet.add(node2.value);
                node2 = node2.next;
            }
            Node start = new Node();
            Node current = start;
            Node before = null;
            for (Integer v : mergeSet) {
                current.value = v;
                Node nextNode = new Node();
                current.next = nextNode;
                before = current;
                current = nextNode;
            }
            before.next = null;
            return start;
        }
        //定义一个链表
        static class Node {
            Node next;
            int value;
    
            public Node(int value) {
                this.value = value;
            }
    
            public Node() {
            }
    
            @Override
            public String toString() {
    
                return value + "->" +
                        (next == null ? "" : next);
            }
        }

    验证:

        public static void main(String[] args) {
            Node node11 = new Node(11);
            Node node12 = new Node(12);
            Node node13 = new Node(11);
            Node node21 = new Node(21);
            Node node22 = new Node(22);
            Node node23 = new Node(22);
    
            node11.next = node12;
            node12.next = node13;
            node21.next = node22;
            node22.next = node23;
    
            MergeLinked mergeLinked = new MergeLinked();
            System.out.println("Node1:" + node11);
            System.out.println("Node2:" + node21);
            System.out.println(mergeLinked.megerLinkedFunc01(node11, node21));
        }

    输出结果:

    11->12->21->22
  • 相关阅读:
    AutoMapper 使用实践
    项目重构之路
    Xamarin对Visual Studio用户免费 Xamarin SDK将开源
    php的文件上传及下载,附带显示文件及目录
    SMARTY静态缓存
    SMARTY的简单实例写法
    SMARTY的知识
    wampserver的使用配置
    php权限管理
    phpcms企业站的一些知识
  • 原文地址:https://www.cnblogs.com/starstarstar/p/11334648.html
Copyright © 2020-2023  润新知