思路:
/**
* 解决思路:
* 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;
}
}
}