在vs2010里,指针声明的时候不赋值也不置NULL是没问题的。不过leetcode上如果不赋值,必须初始化为NULL,不然就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;
}
};
不过还是有一些更简洁的写法:
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;
}