You are given two non-empty linked lists representing two non-negative integers. 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.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
給出了兩個非空鏈表,表示兩個非負整數。數字以倒序存儲,每個節點都包含一個數字。添加兩個數字並將其作爲一個鏈表返回。
提示:本題解法是將兩個鏈表對應的節點進行求和,類似與數學中的2個數相加,注意一點別忽略進位。
public class AddTwoNumbers {
public static ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode result = new ListNode(0);
if(l1 ==null && l2 == null) {
return result.next;
}
ListNode currentNode = result;
int sum = 0;
while(l1 != null || l2 != null || sum != 0) {
if(l1 != null) {
sum += l1.val;
l1 = l1.next;
}
if(l2 != null) {
sum += l2.val;
l2 = l2.next;
}
ListNode node = new ListNode(sum%10);
currentNode.next = node;
currentNode = node;
sum = sum/10;
}
return result.next;
}
public static void main(String[] args) {
ListNode l10 = new ListNode(2);
ListNode l11 = new ListNode(4);
ListNode l12 = new ListNode(3);
l10.next = l11;
l11.next = l12;
l12.next = null;
ListNode l20 = new ListNode(5);
ListNode l21 = new ListNode(6);
ListNode l22 = new ListNode(4);
l20.next = l21;
l21.next = l22;
l22.next = null;
ListNode node = addTwoNumbers(l10, l20);
while(node != null) {
if(node.next == null) {
System.out.println(node.val);
}else {
System.out.print(node.val+"->");
}
node = node.next;
}
}
}
class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
}
}