C++写链表的方式和C语言略有不同,new申请空间,struct内部写构造函数ListNode(int x) : val(x), next(NULL) {},不用刻意把一个节点的next设为null了很方便。
/**
* 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* head=new ListNode(-1);
ListNode* h=head;
int sum=0;
bool carry=false;
while(l1!=NULL||l2!=NULL)
{
sum=0;
if(l1!=NULL)
{
sum+=l1->val;
l1=l1->next;
}
if(l2!=NULL)
{
sum+=l2->val;
l2=l2->next;
}
if(carry) sum++;
h->next=new ListNode(sum%10);
h=h->next;
carry=sum/10;
}
if(carry)
h->next=new ListNode(1);
return head->next;
}
};