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.
思路:
刚开始接触链表的数据结构,还有待进一步理解。这道题目的思路是建立一个新链表,然后把输入的两个链表从头往后遍历,每两个相加,添加一个新街点到新链表后边,但要注意处理进位问题,还有就是最高位的进位要特殊处理一下。
var addTwoNumbers = function(l1, l2) {
var res=new ListNode(-1);//创建新链表
var cur=res;//当前的链表值,最开始指向res的头元素
var carry=0;//进位
while(l1 || l2){
var n1=l1 ? l1.val :0;
var n2=l2 ? l2.val :0;
var sum=n1+n2+carry;
carry=Math.floor(sum/10);//进位
cur.next=new ListNode(sum%10);
cur=cur.next;
if(l1) l1=l1.next;
if(l2) l2=l2.next;
}
if(carry) cur.next=new ListNode(1)
return res.next;
};