LeetCode 2. add two numbers

看似简单,轻易AD,但重点是和其他人写的代码进行比较从而学习

C++:

ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
        ListNode* result;
        ListNode* cur;
        ListNode* cur_1 = l1->next, *cur_2 = l2->next;
        
        int cur_value = l1->val + l2->val;
        int hasOne = cur_value/10;
//      ListNode first();  因为用了cur=&first而不是new导致Runtime Error,个人认为具体原因是出了函数first就被当做临时变量释放
        cur = result = new ListNode(cur_value - hasOne*10);
        
        while (cur_1 != NULL && cur_2 != NULL) {
            cur_value = cur_1->val + cur_2->val + hasOne;
            hasOne = cur_value/10;
            cur->next = new ListNode(cur_value - hasOne*10);
            cur = cur->next;
            cur_1 = cur_1->next;
            cur_2 = cur_2->next;
        }
        
        while(cur_1 != NULL) {
            int tmp = cur_1->val;
            tmp += hasOne;
            hasOne = tmp/10;
            cur_1 = cur_1->next;
            cur->next = new ListNode(tmp-hasOne*10);
            cur = cur->next;
        }
        
        while(cur_2 != NULL){
            int tmp = cur_2->val;
            tmp += hasOne;
            hasOne = tmp/10;
            cur_2 = cur_2->next;
            cur->next = new ListNode(tmp-hasOne*10);
            cur = cur->next;
        }
        
        if (hasOne > 0) {
            cur->next = new ListNode(hasOne);
        }
        
        return result;
    }

笨到家的方法,显然是一个一个特殊情况想起来之后加进去,没有章法。通过别人代码改进后:

ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
        int hasOne = 0;
        ListNode preheader(-1);
        ListNode* cur = &preheader;
        while (l1 || l2 || hasOne) {
            int cur_value = (l1?l1->val:0) + (l2?l2->val:0) + hasOne;
            l1 = l1?l1->next:NULL;
            l2 = l2?l2->next:NULL;
            hasOne = cur_value/10;
            cur->next = new ListNode(cur_value%10);
            cur = cur->next;
        }
        return preheader.next;
    }

1. preheader解决了头结点特殊情况问题

2. 利用 1220 + 12 = 1220 + 0012的办法将多个情况分支融合

Python(自己写的形如c++,但对比方知python代码之简洁):

#from https://leetcode.com/discuss/36908/python-for-the-win
def addTwoNumbers(self, l1, l2): 
  addends
= l1, l2
  dummy = end = ListNode(0)
  carry = 0
  while addends or carry:
    carry += sum(a.val for a in addends)
    addends = [a.next for a in addends if a.next]
    end.next = end = ListNode(carry % 10)
  carry /= 10
  return dummy.next
#version of transfer to int then transfer back
def addTwoNumbers(self, l1, l2): 
    def toint(node): 
        return node.val + 10 * toint(node.next) if node else 0 
    def tolist(n): 
        node = ListNode(n % 10)
        if n > 9: 
            node.next = tolist(n / 10) 
        return node 
return tolist(toint(l1) + toint(l2))                

1. m = n = 1的情况下,n改变m不会跟着改变;m = n = My_Class的情况下,n改变m也会跟着变

2. end.next = end = Class()等价于end.next = Class(); end = end.next;

原文地址:https://www.cnblogs.com/rangozhang/p/4550576.html