第一天 Add Two Numbers(链表加法)

这是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;
 }





  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值