【问题标题】:Why this program is not able to merge 2 Linked List in Sorted order?为什么这个程序不能按排序顺序合并 2 个链表?
【发布时间】:2020-12-15 09:09:17
【问题描述】:

合并两个排序的链表并将其作为新的排序列表返回。应该通过将前两个列表的节点拼接在一起来制作新列表。

例子:

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

【问题讨论】:

  • 问题说要返回一个新的排序列表,但您似乎没有在任何地方创建一个新列表。

标签: c++ algorithm data-structures linked-list singly-linked-list


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2021-12-23
    • 1970-01-01
    • 1970-01-01
    • 2021-12-09
    • 2014-09-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多