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.
Example:
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4) Output: 7 -> 0 -> 8 Explanation: 342 + 465 = 807.
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ class Solution { public ListNode addTwoNumbers(ListNode l1, ListNode l2) { //设置虚拟头结点,便于返回结果 ListNode dummy = new ListNode(-1); ListNode cur = dummy; int carry = 0;//标记进位 //竖式计算 while (l1 != null || l2 != null) { /** *num1,num2从l1,l2链表的第一个数开始遍历相加 *若其中一个链表较短,则在其前面补零 */ int num1 = l1 == null ? 0 : l1.val; int num2 = l2 == null ? 0 : l2.val; int sum = carry + num1 + num2; //相加之数不小于10时,需要计算进位值 carry = sum / 10; //结果链表中保存的实际值为sum取余的结果 cur.next = new ListNode(sum % 10); cur = cur.next; if (l1 != null) { l1 = l1.next; } if (l2 != null) { l2 = l2.next; } } //若最终进位值不为0,则添加新结点保存进位值 if (carry != 0){ cur.next = new ListNode(carry); } return dummy.next; } }