LeetCode算法第二题 "add two sums"

Description

You are given two non-empty linked lists representing two non-negative integers. 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.

You may assume the two numbers do not contain any leading zero, except the number 0 itself.

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

Code

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) {
    struct ListNode* r = (struct ListNode*)calloc(1, sizeof(struct ListNode));
    struct ListNode* p=l1;
    struct ListNode* q=l2;
    struct ListNode* s = r;
    int carry = 0;
    while(p != NULL || q != NULL){
        int x = (p != NULL) ? p->val : 0;
        int y = (q != NULL) ? q->val : 0;
        struct ListNode* t = (struct ListNode*)calloc(1, sizeof(struct ListNode));
        int sum = carry + x + y;
        carry = sum / 10;
        t->val = sum % 10;
        t->next = NULL;
        s->next = t;
        s = t;
        if (p != NULL)
            p = p->next;
        if (q != NULL)
            q = q->next;
    }
    if(carry == 1){
        struct ListNode* t = (struct ListNode*)calloc(1, sizeof(struct ListNode));
        t->val = 1;
        t->next = NULL;
        s->next = t;
    } 
    return r->next;
}

Conclusion

  1. How to create the target list without knowing the actual lengths of the input lists?
  2. Be careful when dealing with the carry.
  3. How to return the correct pointer of the target list? By adding a head of the target list and return from its next.

猜你喜欢

转载自blog.csdn.net/gaussrieman123/article/details/78490882