[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

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

 1 /**
 2  * Definition for singly-linked list.
 3  * struct ListNode {
 4  *     int val;
 5  *     ListNode *next;
 6  *     ListNode(int x) : val(x), next(NULL) {}
 7  * };
 8  */
 9 class Solution {
10 public:
11     ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) {
12         if (l1 == NULL || l2 == NULL)
13             return l1 == NULL ? l2 : l1;
14             
15         int carry = 0;
16         ListNode *pter1 = l1;
17         ListNode *pter2 = l2;
18         ListNode *head = NULL;
19         ListNode **prev= &head;
20         while (pter1 != NULL || pter2 != NULL) {
21             const int l1_val = pter1 == NULL ? 0 : pter1->val;
22             const int l2_val = pter2 == NULL ? 0 : pter2->val;
23             int temp_val = l1_val + l2_val + carry;
24             ListNode *temp_node = new ListNode(temp_val % 10);
25             carry = temp_val / 10;
26             *prev = temp_node;
27             prev = &(temp_node->next);
28             pter1 = pter1 == NULL ? NULL : pter1->next;
29             pter2 = pter2 == NULL ? NULL : pter2->next;
30         }
31         
32         if (carry == 1) {
33             ListNode *temp_node = new ListNode(1);
34             *prev = temp_node;
35         }
36         
37         return head;
38     }
39 };
原文地址:https://www.cnblogs.com/vincently/p/4055340.html