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 res=new ListNode(0);
// carry 中存进位。
int carry =0;
// p 节点用于移动,res 节点用于最终的数据返回。初始状态P节点和res节点位置在一起。
ListNode p = res;
// while 循环中有三个条件,其中,carry !=0 是为了最后有一个进位,还是要进入循环。
while(l1!= null || l2 != null || carry != 0)
{
if(l1!=null)
{
carry =carry +l1.val;
l1=l1.next;
}
if(l2!=null)
{
carry =carry+l2.val;
l2=l2.next;
}
p.next = new ListNode(carry%10);
carry =carry/10;
p =p.next;
}
// 最后返回头结点的下一个节点。
return res.next;
}
}