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


    方法一: 将两个链表放在同一个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
  • 相关阅读:
    nginx配置虚拟主机
    Nginx 目录结构
    Day 12.1模拟赛游记
    Day 11.25模拟赛游记
    Day 11.20模拟赛游记
    Day 11.19模拟赛游记
    Day 11.17模拟赛游记
    【题解报告】P3797 妖梦斩木棒
    8-28练习报告
    二分图匹配与树链剖分
  • 原文地址:https://www.cnblogs.com/starstarstar/p/11334648.html
Copyright © 2020-2023  润新知