c++ - C++ 链表中的虚拟节点

标签 c++ algorithm pointers linked-list

我正在尝试开发一种解决链表问题的方法,而不必以任何特殊方式关心头节点,即在链表问题中,我们通常在开始下一个节点之前单独处理头指针.

我找到了一个方法:使用虚拟节点,使实际链表从 dummy.next 开始。

我正在尝试解决 problem使用这种方式:

 struct ListNode {
     int val;
     ListNode *next;
     ListNode(int x) : val(x), next(NULL) {}
 };

 ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {

        ListNode dummy = ListNode(0);
        ListNode * temp = dummy.next;
        int carry =0;

        while(l1!=NULL && l2!=NULL)
        {
            int x = (l1->val + l2->val + carry)%10;
            temp = new ListNode(x);
            carry = (l1->val + l2->val + carry)/10;
            temp = temp->next;
            l1 = l1->next;
            l2 = l2->next;
        }

        ListNode * p = (l1!=NULL)?l1:l2;

        while(p!=NULL)
        {
            int x = (p->val+carry)%10;
            temp = new ListNode(x);
            carry = (p->val+carry)/10;
            temp = temp->next;
            p = p->next;
        }

        if(carry==1) temp = new ListNode(1);

        return dummy.next;

    }

int main()
{
    ListNode * l1 = new ListNode(0), *l2 = new ListNode(0);
    ListNode * l3 = addTwoNumbers(l1,l2);

}

在这个问题中,我尝试不单独初始化一个头节点。显然,代码没有按照我的意愿执行,但我尝试过这种方式,现在我无法弄清楚如何继续使用这种方法。

即使用dummy节点,这样就不需要单独处理新建链表的头节点。

有什么方法可以使用这种方法来解决问题吗?

最佳答案

遵循这种方法

ListNode * addTwoLists(ListNode * first, ListNode * second) {
    ListNode * res = NULL, * temp, * prev = NULL;
    int carry = 0, sum;
    while (first != NULL || second != NULL) {
        sum = carry + (first ? first->val : 0) + (second ? second->val : 0);
        carry = (sum >= 10) ? 1 : 0;
        sum %= 10;
        temp = new ListNode(sum);
        if (res == NULL)
            res = temp;
        else
            prev->next = temp;
        prev = temp;
        if (first) first = first->next;
        if (second) second = second->next;
    }
    if (carry > 0)
        temp->next = new ListNode(carry);
    return res;
}

关于c++ - C++ 链表中的虚拟节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31491020/

相关文章:

java - 计算器算法 - 在二叉搜索树上使用迭代而不是递归

algorithm - 最佳排序算法——部分排序链表

python - 如何计算最佳列宽?

c++ - 未初始化的局部变量

python - 在客户的基础设施上部署 Tensorflow 应用程序

c++ - 有没有正确的方法在 C++ 中通过引用返回一个新的对象实例?

c++ - 如何在 C 中包含第三方库?

c++ - 我可以在 C++ 中使用指针访问二维数组的元素吗?

c - C是否检查指针是否越界而不取消引用指针?

C++ 指针使用 Visual Studio 更改地址,而不是使用 OsX 中的 Xcode 或 Linux 中的 gcc