leetcode144add-two-numbers

题目描述

给定两个代表非负数的链表,数字在链表中是反向存储的(链表头结点处的数字是个位数,第二个结点上的数字是十位数...),求这个两个数的和,结果也用链表表示。
输入:(2 -> 4 -> 3) + (5 -> 6 -> 4)
输出: 7 -> 0 -> 8

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

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

示例1

输入

复制
{0},{0}

输出

复制
{0}
示例2

输入

复制
{0},{1}

输出

复制
{1}

 

   /**
     *
     * @param l1 ListNode类
     * @param l2 ListNode类
     * @return ListNode类
     */
    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
        // write code here
        //创建结果链表的头结点,默认该节点中的value为-1
        ListNode dummy=new ListNode(-1);
        ListNode pre=dummy;
        //进位标识carry,默认为0
        int carry =0;
        //遍历链表,当两个链表都为空时,退出
        while (l1!=null || l2 !=null){
            //判断该节点是否为空,当节点为空时,用0补全,不为空时,加数即为节点的值
            int d1=(l1==null) ?0:l1.val;
            int d2=(l2==null)? 0:l2.val;
            //对节点求和,注意:求和是需要考虑到进位
            int sum=d1+d2+carry;
            //更新进位标识,
            carry=(sum>=10)?1:0;
            //sum%10标识求和的个位数,将其保存到结果链表中
            pre.next=new ListNode(sum%10);
            pre=pre.next;
            if (l1!=null) l1=l1.next;
            if (l2!=null) l2=l2.next;
            
        }
        //重点  这是一个特殊情况,当两个链表计算完后
        //还需要判断进位标识是否为1,如果为1,如28+81=104,需要创建一个节点保存最高位
        if (carry ==1)
            pre.next=new ListNode(1);
        return dummy.next;
    }

 

/**
 * struct ListNode {
 *    int val;
 *    struct ListNode *next;
 * };
 */

class Solution {
public:
    /**
     *
     * @param l1 ListNode类
     * @param l2 ListNode类
     * @return ListNode类
     */
    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
        // write code here
        ListNode fake(0);
        ListNode *p=&fake;
        int carry=0;
        while (l1 || l2 || carry)
        {
            int sum=(l1?l1->val:0)+(l2?l2->val:0)+carry;
            carry=sum/10;
            p->next=new ListNode(sum%10);
            p=p->next;
            l1=l1?l1->next:nullptr;
            l2=l2?l2->next:nullptr;
            
        }
        return fake.next;
    }
};

posted on 2020-07-20 14:50  滚雪球效应  阅读(138)  评论(0编辑  收藏  举报