题干:
思路很简单,根据链表模拟加法。
wrong:
1.如果对于没申请空间的结构体,进行赋值会报错.
//错误
ListNode *p;
p->next = xxx;
//正确写法
ListNode *p = new ListNode();
p->next = xxx;
代码:
/**
* 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) {
int cnt = 0;
int sum = 0;
ListNode *num1 = l1;
ListNode *num2 = l2;
ListNode *pos = new ListNode(0);
ListNode *ans;
ans = pos;
int a = 0;
int b = 0;
while(num1!=NULL || num2!=NULL){
a = 0;
b = 0;
if(num1!=NULL){a=num1->val;}
if(num2!=NULL){b=num2->val;}
sum = a+b+cnt;
cnt = sum/10;
pos->next = new ListNode(sum%10);
pos = pos->next;
if(num1!=NULL) num1 = num1->next;
if(num2!=NULL) num2 = num2->next;
}
if(cnt>0){
pos->next = new ListNode(cnt%10);
}
return ans->next;
}
};
题目链接: