leetcode算法题-链表-两数之和

题目描述

给出两个 非空 的链表用来表示两个非负的整数。其中,它们各自的位数是按照 逆序 的方式存储的,并且它们的每个节点只能存储 一位 数字。
如果,我们将这两个数相加起来,则会返回一个新的链表来表示它们的和。
您可以假设除了数字 0 之外,这两个数都不会以 0 开头。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/add-two-numbers
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

代码实现

package com.leetcode.链表;

import java.util.List;

/**
 * Author:markusZhang
 * VM Args:
 * Date:Create in 2020/2/2 14:24
 */
public class 两数相加 {
    static class ListNode{
        int val;
        ListNode next;
        public ListNode(){}
        public ListNode(int val){
            this.val = val;
        }
    }
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        if(l1==null){
            return l2;
        }
        if(l2==null){
            return l1;
        }
        boolean isCarry = false;//是否有进位
        ListNode newNode = new ListNode(0);//新链表 存 和
        ListNode pNode = newNode;//遍历节点
        while(l1!=null || l2!=null){
            int sum=0;
            if(l1!=null){
                sum += l1.val;
                l1 = l1.next;
            }
            if(l2!=null){
                sum += l2.val;
                l2 = l2.next;
            }
            if(isCarry){
                sum++;
            }
            pNode.next = new ListNode(sum%10);
            pNode = pNode.next;
            isCarry = sum>=10?true:false;
        }
        if(isCarry){
            pNode.next = new ListNode(1);
        }
        return newNode.next;
    }
}

猜你喜欢

转载自blog.csdn.net/MarkusZhang/article/details/104144895