#2. Add Two Numbers
You are given two linked lists representing two non-negative numbers. 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.
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
思路:两个链表相加,每个节点的数字都为个位数,需要进位。那么相加循环的条件有三个:l1
链表一不为空 l2
链表二不为空 decimal
进位数不为零。
Java Solution(neat)
public class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode pre = new ListNode(0);
ListNode head = pre;
int decimal = 0;
while (l1 != null || l2 != null || decimal != 0) {
ListNode cur = new ListNode(0);
int sum = ((l2 == null) ? 0 : l2.val) + ((l1 == null) ? 0 : l1.val) + decimal;
cur.val = sum % 10;
decimal = sum / 10;
pre.next = cur;
pre = cur;
l1 = (l1 == null) ? l1 : l1.next;
l2 = (l2 == null) ? l2 : l2.next;
}
return head.next;
}
}