自己运行:
提交以后:
代码:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) {
struct ListNode *l,*p;
l = (struct ListNode*)malloc(sizeof(struct ListNode));
l->val = 0;
l->next = NULL;
p = l;
int carry = 0;
while(l1 || l2 || carry){
if(l1){
carry += l1->val;
l1=l1->next;
}
if(l2){
carry += l2->val;
l2=l2->next;
}
p->next = (struct ListNode*)malloc(sizeof(struct ListNode));
p = p->next;
p->val = carry%10;
carry /= 10;
}
return l->next;
}
为什么这个C++的就accepted。哪位能给点提示,谢谢
class Solution {
public:
ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) {
ListNode *l = new ListNode(0), *p = l;
int carry = 0;
while(l1 || l2 || carry) {
if(l1) {
carry+=l1->val;
l1 = l1->next;
}
if(l2) {
carry+=l2->val;
l2 = l2->next;
}
p->next = new ListNode(carry%10);
carry /= 10;
p = p->next;
}
return l->next;
}
};
是这样的,C语言,最后指针的next应该指向NULL,这很重要