思路:
创造一个新的链表,每一个链表对应的位置进行进制的转换,当 L1和L2 第一个相加 7+5 =12, 那么就创建新节点,将12%10=2 放入新节点的val中,然后 L1=L1->next, L2=L2->next;
/**
* 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*ans=new ListNode(0);
int count=0;
ListNode*cur=ans;
while(l1!=NULL || l2!=NULL)
{
int num1=l1 == NULL ? 0 : l1->val;
int num2=l2 == NULL ? 0 : l2->val;
int num=num1+num2+count;
count=num / 10;
//进位
cur->next=new ListNode(num % 10);//
l1=l1==NULL ? NULL :l1->next;
l2=l2==NULL ? NULL :l2->next;
cur=cur->next;//cur更换位置
}
//最后count还有剩余 l1 l2 都循环完了
if(count == 1)
{
cur->next = new ListNode(count);
}
return ans->next;
}
};
如有错误,多多指教!