leetcode链表相加

    科技2022-07-21  106

    /** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode() : val(0), next(nullptr) {} * ListNode(int x) : val(x), next(nullptr) {} * ListNode(int x, ListNode *next) : val(x), next(next) {} * }; */ class Solution { public: ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) { int c = 0; ListNode* dummyNode = new ListNode(-1); ListNode*p = dummyNode; while (l1 || l2) { int a = l1 ? l1->val : 0; int b = l2 ? l2->val : 0; p->next = new ListNode((a + b + c) % 10); p = p->next; c = (a + b + c) / 10; if (l1) { l1 = l1->next; } if (l2) { l2 = l2->next; } } if (c) { p->next = new ListNode(1); } return dummyNode->next; } };
    Processed: 0.013, SQL: 8