2. 两数相加

/**
 * 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) {
        //结果列表
                ListNode *head = new ListNode(0);
                ListNode *presult = head;

                //测量两链表长度
                ListNode *p1=l1, *p2=l2;
                long long int l1count=0, l2count=0;
                while(p1->next!=NULL){
                        p1=p1->next;
                        l1count++;
                }
                while(p2->next!=NULL){
                        p2=p2->next;
                        l2count++;
                }
                //使两链表同长
                long long int i = l2count - l1count;
                if(i>=0){
                        while(i>0){
                                i--;
                                p1->next = new ListNode(0);
                                p1 = p1->next;
                        }
                }
                else{
                        i = -1*i;
                        while(i>0){
                                i--;
                                p2->next = new ListNode(0);
                                p2 = p2->next;
                        }
                }

                //相加
                bool flag=false;
                p1=l1; p2=l2;
                int val;
                while(p1!=NULL){
                        val = p1->val + p2->val;
                        if(flag) val++;
                        if(val > 9){
                                val -= 10;
                                flag = true;
                        }
                        else 
                                flag=false;
                        presult->next = new ListNode(val);
                        presult = presult->next;
                        p1=p1->next; p2=p2->next;

                        if(flag)
                                presult->next = new ListNode(1);
                }

                return head->next;
    }
};