【LeetCode】2. 两数相加(Add Two Number

2020-06-15  本文已影响0人  仍有不归期

简书内代码已上传GitHub:点击我 去GitHub查看代码
点击 这里跳转到LeetCode官网查看题目
点击 这里跳转到LeetCode中国官网查看题目

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.

中文:

给出两个 非空 的链表用来表示两个非负的整数。其中,它们各自的位数是按照 逆序 的方式存储的,并且它们的每个节点只能存储 一位 数字。

如果,我们将这两个数相加起来,则会返回一个新的链表来表示它们的和。

您可以假设除了数字 0 之外,这两个数都不会以 0 开头。

示例:

输入:(2 -> 4 -> 3) + (5 -> 6 -> 4)
输出:7 -> 0 -> 8
原因:342 + 465 = 807

思路:

Accept by C:

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */


struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2){
    struct ListNode* l3, *h = l1,*endnode = (struct ListNode*)malloc(sizeof(struct ListNode));
    // 进位标志
    int carry = 0;
    //遍历l1
    while(l1){
        //每一位的和
        int nextval = (l1 ? l1 -> val : 0) + (l2 ? l2 -> val : 0) + carry;
        l1 -> val = nextval % 10;
        // 进位
        carry = nextval / 10;
        // 保存l1,用于衔接l2
        l3 = l1;
        l1 = l1 -> next;
        // l2非空,遍历
        if(l2) l2 = l2 -> next;
        // l2比l1长,剩余部分接到l1后面,继续遍历
        if(!l1 && l2){
            //衔接
            l1 = l3 -> next = l2;
            l2 = NULL;
        }
    }
    //最后一位进位操作
    if(carry){
        endnode -> val = carry;
        endnode -> next = NULL;
        l3 -> next = endnode;
    }
    return h;

}

每天进步一点,加油!


End

END

上一篇 下一篇

猜你喜欢

热点阅读