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.
思路:
剛開始接觸鏈表的數(shù)據(jù)結(jié)構(gòu)虫碉,還有待進(jìn)一步理解内狸。這道題目的思路是建立一個(gè)新鏈表,然后把輸入的兩個(gè)鏈表從頭往后遍歷纬黎,每兩個(gè)相加,添加一個(gè)新街點(diǎn)到新鏈表后邊孽水,但要注意處理進(jìn)位問題陕贮,還有就是最高位的進(jìn)位要特殊處理一下。
var addTwoNumbers = function(l1, l2) {
var res=new ListNode(-1);//創(chuàng)建新鏈表
var cur=res;//當(dāng)前的鏈表值甜滨,最開始指向res的頭元素
var carry=0;//進(jìn)位
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);//進(jìn)位
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;
};