Add Two Numbers

思路:

/**
 * 解决思路:
 * 1.判断链表是否为空
 * 2.判断链表长度是否相等
 * 3.相加的时候判断两个值之和是否大于10
 *
 */

package com.example.lib2;

public class myClass {

static class ListNode {
int val;
ListNode next;
ListNode(int x) { val = x; }
}

public static void main(String[] args) {

 ListNode l1 =  new ListNode(2);
 ListNode l2 =  new ListNode(4);
 ListNode l3 =  new ListNode(3);

l1.next = l2;
l2.next = l3;



 ListNode l5 =  new ListNode(5);
ListNode l6 =  new ListNode(6);
ListNode l7 =  new ListNode(4);

    l5.next = l6;
    l6.next = l7;


    ListNode l9 = null;
    ListNode addNode = Solution.addTwoNumbers(l1,l5);

    while (addNode != null ) {

        System.out.println(addNode.val);
        addNode = addNode.next;
    }

}
/**
 * 解决思路:
 * 1.判断链表是否为空
 * 2.判断链表是否相等
 * 3.相加的时候判断两个值之和是否大于10
 *
 * 1 3 5 7
 * 2 4 6
 */
static class Solution {
    public static ListNode addTwoNumbers(ListNode l1, ListNode l2) {

        if (l1 == null) {
            return l2;
        }else if (l2 == null) {
            return l1;
        }

        ListNode head = new ListNode(-1);
        ListNode current = head;
        int up = 0;
        while(l1 != null && l2 != null) {

            // 2 4 3      5 6 4

            int value = (l1.val +l2.val +up) % 10;
            ListNode node =  new ListNode(value);
            up = (l1.val +l2.val)/10;
            current.next = node;
            current = current.next;

            l1 = l1.next;
            l2 = l2.next;
        }

        while (l1 != null) {

            ListNode node =  new ListNode(l1.val);
            current.next = node;
            current = current.next;
            l1 = l1.next;
        }

        while (l2 != null) {

            ListNode node =  new ListNode(l2.val);
            current.next = node;
            current = current.next;
            l2 = l2.next;
        }

        return head.next;
    }
}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值