首页 > 代码库 > [LeetCode] Add Two Numbers

[LeetCode] Add Two Numbers

You are given two linked lists representing two non-negative numbers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8

 

思路:两条链表相加,注意最后如果进位不为零,要加入到结果中。使用二级指针记录节点前缀。

/** * Definition for singly-linked list. * struct ListNode { *     int val; *     ListNode *next; *     ListNode(int x) : val(x), next(NULL) {} * }; */class Solution {public:    ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) {        if (l1 == NULL || l2 == NULL) {            return l1 == NULL ? l1 : l2;        }                int carry = 0;        ListNode *head = NULL;        ListNode **prev = &head;                while (l1 != NULL || l2  != NULL) {            int sum = carry;                        int l1_val = 0;            if(l1 != NULL) {                l1_val = l1->val;                l1 = l1->next;            }                        int l2_val = 0;            if (l2 != NULL) {                l2_val = l2->val;                l2 = l2->next;            }                        sum += l1_val + l2_val;            ListNode *pt = new ListNode(sum % 10);            *prev = pt;            prev = &(pt->next);            carry = sum / 10;        }                if (carry) {            ListNode *pt = new ListNode(carry);            *prev = pt;        }                return head;    }};

 

《LeetCode 题解 (C++版)》(戴方勤 著 )中一种非常简洁的写法:

 1 class Solution { 2 public: 3 ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) { 4     ListNode head(-1); // 头节点 5     int carry = 0; 6     ListNode *prev = &head; 7     for (ListNode *pa = l1, *pb = l2; 8     pa != nullptr || pb != nullptr; 9     pa = pa == nullptr ? nullptr : pa->next,10     pb = pb == nullptr ? nullptr : pb->next,11     prev = prev->next) {12         const int ai = pa == nullptr ? 0 : pa->val;13         const int bi = pb == nullptr ? 0 : pb->val;14         const int value = http://www.mamicode.com/(ai + bi + carry) % 10;15         carry = (ai + bi + carry) / 10;16         prev->next = new ListNode(value); // 尾插法17     }18     if (carry > 0)19     prev->next = new ListNode(carry);20 21     return head.next;22     }23 };

 

  

[LeetCode] Add Two Numbers