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 contains a single digit. Add the two numbers and return the sum as a linked list.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
val은 0 이상 9 이하의 정수기본 전략
받아올림 전략 (다음 노드 만들기 전략)
val 값이 10 이상일 경우, 다음 노드의 초기값을 1로 한다. 그리고 현재 노드는 10을 뺀다.val 값이 10 미만일 경우, 다음 노드의 초기 값을 0으로 한다.class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode head = new ListNode(l1.val + l2.val);
l1 = l1.next; l2 = l2.next;
ListNode currentNode = head;
while (l1 != null || l2 != null) {
currentNode = makeNextNode(currentNode);
if (l1 != null) {
currentNode.val += l1.val;
l1 = l1.next;
}
if (l2 != null) {
currentNode.val += l2.val;
l2 = l2.next;
}
}
if (currentNode.val >= 10) {
currentNode = makeNextNode(currentNode);
}
return head;
}
private ListNode makeNextNode(ListNode tailNode) {
ListNode nextNode = new ListNode(tailNode.val / 10);
tailNode.val %= 10;
tailNode.next = nextNode;
return nextNode;
}
}
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
