为什么这个程序不能按排序顺序合并 2 个链表?

Why this program is not able to merge 2 Linked List in Sorted order?

合并两个已排序的链表,return将其作为一个新的已排序链表。新列表应该由前两个列表的节点拼接而成。

示例:

Input: 1->2->4, 1->3->4
Output: 1->1->2->3->4->4
class Solution {
 public:
  ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
    ListNode* temp = l1;
    while(temp->next) {
      temp = temp->next;
    }
    temp->next = l2;
            
    ListNode* a = l1;
    ListNode* b;
    while(a) {
      b = a->next->next;
      if (a->val >= a->next->val) {
        a->next->next = a;
        a->next = b;
      }
      a=a->next;
    }
    return l1;
  }
};

我无法找出这个错误。

Line 27: Char 21: runtime error: member access within null pointer of type 'ListNode' (solution.cpp)
SUMMARY: UndefinedBehaviorSanitizer: undefined-behavior prog_joined.cpp:36:21

在您的 while 循环中,您总是假设 a->next 不为空,因为您调用了 a->next->next。但是,当 a 指向列表中的最后一个元素时,a->next 将为空。

此外,您似乎正在尝试实施冒泡排序,但这需要列表的多次迭代才能正常工作。输入 10->20->30, 1->2->3 将无法正确排序。