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.
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Input: (9->9) + (1)
Output: 0->0->1
该题要求考虑进位。测试用例:链表长度不相等时;最后一次相加有进位时等。
注意: 如何new一个新的链表节点;设置p指针时不能少了*号;->的使用,而不是用 . 。
/**
* 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) {
ListNode* p1 = l1;
ListNode* p2 = l2;
ListNode* l3 = new ListNode(0);
ListNode* p3 = l3;
int carry = 0;//进位
while(p1 != NULL || p2 != NULL){ //只要还有一个链表不为空,就计算sum;而且不要去判断p1->next是不是为空!
int sum = 0; //还有种不用谢carry的写法:while外面写int sum=0;里面写sum /= 10;
if(p1 != NULL){
sum += p1->val;
p1 = p1->next;
}
if(p2 != NULL){
sum += p2->val;
p2 = p2->next;
}
sum += carry;
carry = sum/10;
p3->next = new ListNode(sum % 10);
p3 = p3->next;
}
if(carry == 1){//最后一个值还要进位
p3->next = new ListNode(1);
}
return l3->next;
//return l3; //错误结果为[0,7,0]
}
};
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
ListNode* l3 = new ListNode(0);
ListNode* p = l3;
int carry = 0; //进位
while(l1 || l2 || carry){ //l1、l2、进位均不为空时
int sum = (l1 ? l1->val : 0) + (l2 ? l2->val : 0) + carry;//如果l1不空取当前val值,否则赋值为0
carry = sum/10;
p->next = new ListNode(sum%10);
p = p->next;
l1 = l1 ? l1->next : l1; //如果l1不空往下移,否则不移动
l2 = l2 ? l2->next : l2;
}
return l3->next;
}
};