Description:
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.
就是两个链表相加,低位在前高位在后,相加后还有进位。这个题与另外做过的两道题67. Add Binary和21. Merge Two Sorted Lists。
在Add Binary中也是做加法,在 Add Two Numbers中用到了和Add Binary中类似的while循环;Merge Two Sorted Lists是将两个排序好的链表合并成一个从大到小排列的链表,这道题用到了Merge Two Sorted Lists的新建节点。
/**
* 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 prehead(0),*head = &prehead;
int carry = 0;
while(l1!=NULL || l2!=NULL || carry!=0){//当l1、l2、carry都空时再退出循环
//carry与l1 l2 的值都相加,随后直接判断carry的值
if(l1!=NULL) carry += l1->val;
if(l2!=NULL) carry += l2->val;
if(carry>=10){
head->next = new ListNode(carry%10);//这个地方纠结了很久,想不到怎么扩展链表,其实直接新建一个节点就好了
carry = carry/10;
}
else if(carry<10){
head->next = new ListNode(carry);
carry = 0;
}
if(l1!=NULL) l1 = l1->next;//这个地方注意,当l1 l2 为空时,再让它们指向下一个节点会报错,因为已经指向空了。所以l1 l2指针下移时要有判定
if(l2!=NULL) l2 = l2->next;
head = head->next;
}
if(carry!=0) head->next = new ListNode(carry);
return prehead.next;
}
};