In vs2010, it is no problem to have the pointer declared without assigning a value and pail null. However, if you do not assign a value on the Leetcode, it must be initialized to null, or re.
/** * 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 *res = NULL;
if (!L1) {res = L2;return res;
} if (!L2) {res = L1;return res;
} ListNode *p = NULL;
int carry = 0, tmp;
while (L1 && L2) {tmp = L1->val + l2->val + carry;
carry = TMP/10;
TMP%= 10;
if (!p) {p = new ListNode (TMP);
res = p;
}else{ListNode *ntmp = new ListNode (TMP);
P->next = ntmp;
p = ntmp;
} L1 = l1->next;
L2 = l2->next;
} while (L1) {tmp = l1->val + carry;
carry = TMP/10;
TMP%= 10;
if (!p) {p = new ListNode (TMP);
res = p;
}else{ListNode *ntmp = new ListNode (TMP);
P->next = ntmp; p = Ntmp
} L1 = l1->next;
} while (L2) {tmp = l2->val + carry;
carry = TMP/10;
TMP%= 10;
if (!p) {p = new ListNode (TMP);
res = p;
}else{ListNode *ntmp = new ListNode (TMP);
P->next = ntmp;
p = ntmp;
} L2 = l2->next;
} if (carry>0) {ListNode *ntmp = new ListNode (carry);
P->next = ntmp;
} return res; }
};
However, there are some more concise wording:
Public ListNode addtwonumbers (listnode L1, ListNode L2) {
ListNode current = new ListNode (0);
ListNode head = current;
int shift = 0;
Do
{
current.val = ((l1!=null) l1.val:0) + ((l2!=null)? l2.val:0) + Shift;
shift = CURRENT.VAL/10;
current.val%=10;
L1 = (l1!=null)? L1.next:null;
L2 = (l2!=null)? L2.next:null;
if ((l1==null) && (l2==null)) {break;}
Current.next = new ListNode (0);
current = Current.next;
} while (L1!=null | | l2!=null);
if (shift>0) {current.next = new ListNode (1);}
return head;
}