lintcode-链表求和

http://www.lintcode.com/zh-cn/problem/add-two-numbers/

两个链表求和,我们只需要模仿CPU里的加法器,设置一个S位,一个C位进位即可

/**
 * Definition of singly-linked-list:
 * class ListNode {
 * public:
 *     int val;
 *     ListNode *next;
 *     ListNode(int val) {
 *        this->val = val;
 *        this->next = NULL;
 *     }
 * }
 */

class Solution {
public:
    /**
     * @param l1: the first list
     * @param l2: the second list
     * @return: the sum list of l1 and l2 
     */
    ListNode * addLists(ListNode * l1, ListNode * l2) {
        int c = 0, s = 0;
        ListNode *p = l1, *q = l2, *result = new ListNode(0), *a = nullptr;
        a = result;
        while(p || q){
            s = c;
            if(p){
                s += p->val;
                p = p->next;
            }
            if(q){
                s += q->val;
                q = q->next;
            }
            if(s >= 10){
                s %= 10;
                c = 1;
            }else{
                c = 0;
            }
            a->next = new ListNode(s);
            a = a->next;
        }
        if(c){
            a->next = new ListNode(c);
        }
        return result->next;
    }
};

你可能感兴趣的:(数据结构)