SA-SSD程式碼閱讀
阿新 • • 發佈:2020-12-30
2. 兩數相加
思路:
建立一個新的連結串列,專門用來儲存兩個連結串列對應數字的和,並判斷是否大於等於10,是否需要進位
1、定義當前節點及下標
2、迴圈兩個連結串列l1,l2(兩個類)得到他們的 val
3、當前值加上curListNodeIndex
4、當前節點值取模curListNode.next=newListNode(sum%10)
5、取整獲取節點下標curListNodeIndex=Math.floor(sum/10)
6、判斷curListNodeIndex 大於零的情況 就往上加一個節點
程式碼:
/** * Definition for singly-linked list. * function ListNode(val, next) { * this.val = (val===undefined ? 0 : val) * this.next = (next===undefined ? null : next) * }*/ /** * @param {ListNode} l1 * @param {ListNode} l2 * @return {ListNode} */ var addTwoNumbers = function(l1, l2) { let dummy = new ListNode(); let curListNode = dummy; let curListNodeIndex = 0; while(l1!==null || l2!==null){ let sum = 0; if(l1!==null) { sum+= l1.val; l1 = l1.next; } if(l2!==null) { sum += l2.val; l2 = l2.next; } sum += curListNodeIndex; curListNode.next = new ListNode(sum % 10); curListNodeIndex = Math.floor(sum/10); curListNode = curListNode.next; } if(curListNodeIndex >0) { curListNode.next= new ListNode(curListNodeIndex); } return dummy.next; };