Add Two Numbers

You are given two linked lists representing two non-negative numbers.

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

以下是c++代码

/**
 * 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) {
        int d=0;
    	ListNode *res=new ListNode(0);
    	ListNode *head=res;
    	while(l1&&l2){
    		int added=l1->val+l2->val+d;
    		res->next=new ListNode(added%10);
    		d=added/10;
    		res=res->next;
            l1=l1->next;
            l2=l2->next;
    	}
    	while(l1){
    		int added=l1->val+d;
    		res->next=new ListNode(added%10);
    		d=added/10;
    		res=res->next;
            l1=l1->next;
    	}
    	while(l2){
    		int added=l2->val+d;
    		res->next=new ListNode(added%10);
    		d=added/10;
    		res=res->next;
            l2=l2->next;
    	}
    	if(d==1){
    		res->next=new ListNode(d);
    	}
        return head->next;
    }
};

你可能感兴趣的:(number)