Share my solution with c++


  • 1
    Z

    my solution with c++

    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
        // 算法思路,两两相加,尾部插入
        ListNode *ret_head= 0, *ret_tail = 0;
        int inc = 0;
        
        while(l1 || l2 || inc)
        {
            int val = inc;
            if(l1)
            {
                val += l1->val;
                l1 = l1->next;
            }
            if(l2)
            {
                val += l2->val;
                l2 = l2->next;
            }
            
            inc = 0;
            // 计算值
            if(val >= 10)
            {
                inc = 1;
                val -= 10;
            }
            
            ListNode *t = new ListNode(val);
            if(ret_head == 0)
            {
                ret_head = t;
                ret_tail = t;
            }
            else
            {
                ret_tail->next = t;
                ret_tail = t;
            }
        }
        
        return ret_head;
    }

  • 0
    L

    很简洁,思路也更容易理解。学习了


  • 0
    S

    care to translate to english before sharing.


  • 0
    H

    // 算法思路,两两相加,尾部插入 --- the idea of this algorithm: plus the value of nodes at same "index", and then insert a list node to the end of the list

    // 计算值 -- calculate the value

    I think it's what they mean...


  • 0
    K

    漂亮的解法。给你点个赞!


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.