1. public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
    2. if (list1 == null && list2 == null) {
    3. return null;
    4. }
    5. List<ListNode> node = new ArrayList<>();
    6. while (list1 != null) {
    7. node.add(list1);
    8. list1 = list1.next;
    9. }
    10. while (list2 != null) {
    11. node.add(list2);
    12. list2 = list2.next;
    13. }
    14. Collections.sort(node, new Comparator<ListNode>() {
    15. @Override
    16. public int compare(ListNode o1, ListNode o2) {
    17. return o1.val - o2.val;
    18. }
    19. });
    20. ListNode res = node.get(0);
    21. ListNode tail = res; //链表头引用
    22. for (int i = 1; i < node.size(); i++) {
    23. res.next = node.get(i);
    24. res = res.next;
    25. }
    26. return tail;
    27. }

    错例示范
    问题

    我理解LinkedList的概念,但我仍然不明白如何将整数列表转换为相同的LinkedList!你知道吗 我已经试着在网上阅读了一些关于这方面的信息,我看到有一些递归选项可用,但递归是v.v.昂贵的,我不是它的超级粉丝。下面是LeetCode对LinkedList的实现,以及我将列表转换为LinkedList的方法

    1. # Definition for singly-linked list.
    2. # class ListNode(object):
    3. # def __init__(self, x):
    4. # self.val = x
    5. # self.next = None
    6. list1 = [4,5,1,2,0,4]
    7. head = ListNode(list1[0])
    8. e = 1
    9. while e < len(list1):
    10. print(head)
    11. head.next = ListNode(list1[e])
    12. head = head.next
    13. e+=1
    14. return head

    回答

    1. 问题是您缺少对列表头的引用,因为您正在覆盖它。从这个开始:
    2. list1 = [4,5,1,2,0,4]
    3. head = ListNode(list1[0])
    4. tail = head
    5. 然后tail将引用链表的最后一个元素。现在在你的循环中你做到了:
    6. while e < len(list1):
    7. print(head)
    8. tail.next = ListNode(list1[e])
    9. tail = tail.next
    10. e+=1
    11. 所以您可以像以前一样向列表中添加一个元素,但是现在我们正在修改tail变量。最后:
    12. return head
    13. 现在将返回列表的头节点。你知道吗