Add Two Numbers 【待优化】

You are given two linked lists representing two non-negative numbers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8

思路:注意检查validation!因为都是digit,在%和/可以改成bit opertiaon 来提高效率 【待优化】

/**
 * 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) {
        //check invalidation
        if(l1==NULL) return l2;
        if(l2==NULL) return l1;
        ListNode *rel,*head;
        rel=head=new ListNode(0);
        ListNode *p1=l1;
        ListNode *p2=l2;
        int carry=0;
        int sum=0;
        while(p1&&p2){
            sum = p1->val+p2->val+carry;
            ListNode *node = new ListNode(0);
            node->val = sum%10;
            carry = sum/10;
            rel->next=node;
            
            rel=rel->next;
            p1=p1->next;
            p2=p2->next;
        }
        
        //when p1.length != p2.length
        ListNode *p;
        if(p1==NULL) p=p2;
        else p=p1;
        while(p)
        {
            sum = p->val+carry;
            ListNode *node = new ListNode(0);
            node->val = sum%10;
            carry = sum/10;             
            rel->next=node;
            rel=rel->next;
            p=p->next;
        }
        
        //when highest bit needs carrying operation
        if(carry!=0){
            ListNode *node = new ListNode(0);
            node->val = carry;
            rel->next=node;
        }
        
        return head->next;
        
    }
};
原文地址:https://www.cnblogs.com/renrenbinbin/p/4384983.html