题目
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,若是1 将1放到生成链表最高位。
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
ListNode* sum = new ListNode(0);
ListNode* p = sum;
int temp = 0;
int val1 = 0;
int val2 = 0;
while(l1 != NULL || l2 != NULL){
val1 = 0;
if(l1 != NULL){
val1 = l1->val;
l1 = l1->next;
}
val2 = 0;
if(l2 != NULL){
val2 = l2->val;
l2 = l2->next;
}
p->next = new ListNode((val1+val2+temp)%10);
temp = (val1+val2+temp)/10;
p = p->next;
}
if(temp){
p->next = new ListNode(temp);
}
return sum->next;
}
};