链接:
https://leetcode-cn.com/problems/add-two-numbers/
题目描述:
给你两个 非空 的链表,表示两个非负的整数。它们每位数字都是按照 逆序 的方式存储的,并且每个节点只能存储 一位 数字。
请你将两个数相加,并以相同形式返回一个表示和的链表。
你可以假设除了数字 0 之外,这两个数都不会以 0 开头。
思路跟 989.数组形式的整数加法 一致,只不过将数组换为链表。
需要注意的地方是对链表尾部的处理,以及最后一个结点计算完如果还有进位的话要新建一个结点储存进位值。
代码如下。
public class Problem2 {
public static void main(String[] args) {
ListNode l1 = new ListNode(9);
ListNode l2 = new ListNode(9);
ListNode next;
next = l1;
for (int i = 0; i < 6; i++) {
ListNode node = new ListNode(9);
next.next = node;
next = next.next;
}
next = l2;
for (int i = 0; i < 3; i++) {
ListNode node = new ListNode(9);
next.next = node;
next = next.next;
}
ListNodePrint(l1);
ListNodePrint(l2);
ListNodePrint(addTwoNumbers(l1, l2));
}
public static void ListNodePrint(ListNode node) {
while (node != null) {
System.out.print(node.val);
node = node.next;
}
System.out.println();
}
public static ListNode addTwoNumbers(ListNode l1, ListNode l2) {
if (l1 == null)
return l2;
else if (l2 == null)
return l1;
ListNode next1 = l1, next2 = l2;
int mod = 0;
while (true) {
next1.val = next1.val + next2.val + mod;
mod = next1.val / 10; //0|1
next1.val %= 10;
if (next1.next == null && next2.next == null) {
if (mod == 0)
break;
next1.next = new ListNode(mod);
next1 = next1.next;
break;
}
if (next1.next == null) {
ListNode node = new ListNode(0);
next1.next = node;
}
if (next2.next == null) {
ListNode node = new ListNode(0);
next2.next = node;
}
next1 = next1.next;
next2 = next2.next;
}
return l1;
}
public static class ListNode {
int val;
ListNode next;
public ListNode() {
}
public ListNode(int val) {
this.val = val;
}
public ListNode(int val, ListNode next) {
this.val = val;
this.next = next;
}
}
}
原文:https://www.cnblogs.com/runwithwind/p/14322141.html