首页 > 解决方案 > 如何从 2 个排序的链表中构造一个最大和路径链表?

问题描述

我正在尝试返回一个已排序的链表,该链表在 2 个已排序的链表中具有最大总和路径。该函数如下所列: 它以两个起始列表作为参数。

我总是收到 Segmentation Fault 错误提示。

List MaxSumPath(List l1, List l2)  {

    List l3;
    Node* temp1 = l1.head;
    Node* temp2 = l2.head;

    Node* path1 = temp1;
    Node* path2 = temp2;

    while(temp1 != 0 || temp2 != 0) {


        int sum1 = 0;
        int sum2 = 0;

        while (temp1 != 0 && temp2 != 0 && temp1->data != temp2->data) {

            sum1 += temp1->data;
            path1->next = temp1;
            temp1 = temp1->next;

            sum2 += temp2->data;
            path2->next = temp2;
            temp2 = temp2->next;
        }

        if (sum1 > sum2) {
            while (path1 != 0) {
                l3.AddToTail(path1->data);
                path1 = path1->next;
            }
        } else {
            while (path2 != 0) {
                l3.AddToTail(path2->data);
                path2 = path2->next;
            }
        }

        if (temp1 == 0) {
            while (temp2 != 0) {
                l3.AddToTail(temp2->data);
                temp2 = temp2->next;
            }
        }

        if (temp2 == 0) {
            while (temp1 != 0) {
                l3.AddToTail(temp1->data);
                temp1 = temp1->next;
            }
        }
    }
    return l3;
}

我希望 l3 保存生成的链表。

完整的源代码

标签: c++

解决方案


推荐阅读