2. Add Two Numbers (c++)
??You are given two non-empty linked lists representing two non-negative integers. 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.
??You may assume the two numbers do not contain any leading zero, except the number 0 itself.
Example:
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.
題意:給兩個非空鏈表凯砍,表示兩個非負整數(shù)休吠。數(shù)字存儲方式與數(shù)字順序相反(即向右進位),每個節(jié)點都包含一個數(shù)字奠骄。將兩個數(shù)字相加,并將其作為鏈表返回业踏。
思路:新建一個鏈表res扑媚;每一位相加俏拱,以變量carry保存是否進位,保存每一位相加的結(jié)果sum在res鏈表上察净。最后一位判斷carry是否為1驾茴,是的話res鏈表再添一個val為1的節(jié)點。
class Solution {
public:
ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) {
ListNode *res = new ListNode(0);
ListNode *cur = res;
int sum = 0;
int carry = 0;
while (l1 || l2) {
int n1 = l1->val ? l1->val : 0;
int n2 = l2->val ? l2->val : 0;
sum = n1 + n2 + carry;
carry = sum / 10;
cur->next = new ListNode(sum % 10);
cur = cur->next;
if (l1) {
l1 = l1->next;
}
if (l2) {
l2 = l2->next;
}
}
if (carry) {
cur->next = new ListNode(1);
}
return res->next;
}
};