Add Two Numbers(两个链表求和)

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.

Example

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.

思路:遍历链表的时候各位求和,大于10向高位进位,考虑两个链表不一样长的情况。

C:carry为进位标志

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) {
   struct ListNode *l1_index,*l2_index,*l,*p;
    l = (struct ListNode*)malloc(sizeof(struct ListNode));
    p = l;
    int carry = 0;

    l1_index = l1;
    l2_index = l2;

    while (l1_index != NULL || l2_index != NULL){

        if(l1_index == l1 && l2_index == l2){
            l->val = l1_index->val + l2_index->val;

            //进位标志
            if(l->val >= 10){
                carry = 1;
                l->val %= 10;
            }

            l1_index = l1_index->next;
            l2_index = l2_index->next;
            continue;

        }
        if(l1_index == NULL){
            //先创建一个节点
            struct ListNode *q;
            q = (struct ListNode*)malloc(sizeof(struct ListNode));
            p->next = q;
            p = q;

            p->val = l2_index->val + carry;
            if(p->val >= 10){
                p->val %= 10;
                carry = 1;
            }else{
                carry = 0;
            }
            l2_index = l2_index->next;
            continue;

        } else if(l2_index == NULL){
            //先创建一个节点
            struct ListNode *q;
            q = (struct ListNode*)malloc(sizeof(struct ListNode));
            p->next = q;
            p = q;

            p->val = l1_index->val + carry;
            if(p->val >= 10){
                p->val %= 10;
                carry = 1;
            }else{
                carry = 0;
            }
            l1_index = l1_index->next;
            continue;

        } else{
            //先创建一个节点
            struct ListNode *q;
            q = (struct ListNode*)malloc(sizeof(struct ListNode));
            p->next = q;
            p = q;

            p->val = l1_index->val + l2_index->val;
            p->val += carry;
            if(p->val >= 10){
                p->val %= 10;
                carry = 1;
            }else{
                carry = 0;
            }
            l1_index = l1_index->next;
            l2_index = l2_index->next;
            continue;

        }

    }
    if(carry == 1){
        //先创建一个节点
        struct ListNode *q;
        q = (struct ListNode*)malloc(sizeof(struct ListNode));
        p->next = q;
        p = q;

        p->val = carry;
    }
    p->next = NULL;
    return l;
}
点赞