方法一: 将两个链表放在同一个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