这是leetcode第二题,对链表的知识基础有一定要求。暂时自己写不出来,先完全解析别人的代码。
1. 先排除极端情况,简化后续
<span style="font-size:14px;"> if(l1 == NULL && l2) return l2;
if(l1 && l2 == NULL) return l1;
if(l1 == NULL && l2 == NULL) return NULL;</span>
2. p1,p2为了避免对原输入的影响;head用于最后的输出;c是进位问题;r是随着链表深入下去;bUseList2是决定r沿着l1或者l2进行
由于l1,l2有完整的链表体系,所以沿着l1,l2的next可以避免新生成对象的麻烦。换而言之,借用现有的“变量”l1或者l2,修改成为result
<span style="font-size:14px;"> ListNode * p1 = l1;
ListNode * p2 = l2;
ListNode *r = l1; // r indicates the node space we will use for one digit of the result.
ListNode *head = r; // head is the result list.
bool bUseList2 = false; // Use this to indicate whether we should start to use l2 as resource pool.
int c = 0;</span>
3. while语句表达了三种情况,即l1,l2耗尽以及没有进位的情况(考虑:怎么处理l1,l2同时耗尽且进位的情况);r = r->next正是借用l1,l2的巧妙之处。
<span style="font-size:14px;">while(p1 || p2 || c){
int v = c;
if(p1) v += p1->val;
if(p2) v += p2->val;
c = v >= 10? 1: 0;
r->val = v % 10;
if(p1) p1 = p1->next;
if(p2) p2 = p2->next;
// If we haven't started to used l2, and we have reached the tail of l1,
// switch l2 for the next result digit.
if(bUseList2 == false && r->next == NULL){
r->next = l2;
bUseList2 = true;
}
if(p1 || p2 || c)
r = r->next;
}</span>
最后把r->next用NULL堵上即可。
完整代码如下:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
// first take care of the empty list cases.
if(l1 == NULL && l2) return l2;
if(l1 && l2 == NULL) return l1;
if(l1 == NULL && l2 == NULL) return NULL;
ListNode * p1 = l1;
ListNode * p2 = l2;
ListNode *r = l1; // r indicates the node space we will use for one digit of the result.
ListNode *head = r; // head is the result list.
bool bUseList2 = false; // Use this to indicate whether we should start to use l2 as resource pool.
int c = 0;
while(p1 || p2 || c){
int v = c;
if(p1) v += p1->val;
if(p2) v += p2->val;
c = v >= 10? 1: 0;
r->val = v % 10;
if(p1) p1 = p1->next;
if(p2) p2 = p2->next;
// If we haven't started to used l2, and we have reached the tail of l1,
// switch l2 for the next result digit.
if(bUseList2 == false && r->next == NULL){
r->next = l2;
bUseList2 = true;
}
if(p1 || p2 || c)
r = r->next;
}
// Set the tail of the result list to NULL.
r->next = NULL;
return head;
}