標籤:

leetcode-2

用鏈表實現加法運算

function ListNode(val) {n this.val = val;n this.next = null;n}nfunction isInstance(obj){ntreturn (obj instanceof ListNode);n}nvar addTwoNumbers = function(l1, l2) {nt//判斷參數是否非法ntvar hasL1 = isInstance(l1);ntvar hasL2 = isInstance(l2);ntvar resL = new ListNode(0);nnt//如果兩個參數都不存在的話ntif(!hasL1 && !hasL2){ nttreturn resL;nt}nnt//只有l1存在的話ntif(hasL1 && !hasL2){nttreturn l1;nt}nt//只有l2存在的話ntif(hasL2 && !hasL1){nttreturn l2;nt}nntvar currNode1 = l1;ntvar currNode2 = l2;ntcurrNode = resL;ntntwhile(currNode1 || currNode2){ntt//獲取兩的值的和nttvar value1 = getNodeValue(currNode1);nttvar value2 = getNodeValue(currNode2);nttvar value = value1 + value2;nnttcurrNode.val = value;ntt//l1和l2有下一個節點才需要增加一個新節點nttif(hasNextNode(currNode1)|| hasNextNode(currNode2)){ntttvar newNode = new ListNode(0);ntttcurrNode.next = newNode;ntttcurrNode = currNode.next;//讀取下一個節點ntt}nttttnttif(currNode1){ntttcurrNode1 = currNode1.next;ntt}nnttif(currNode2){ntttcurrNode2 = currNode2.next;ntt}nnt}nntcurrNode = resL;nntwhile(currNode){nttvar currValue = currNode.val; nttif(currValue >= 10){//currNode.val>=10 則 nextNode.val ++;nntttvar nextNode = currNode.next;//獲取下一個節點nntttif(!nextNode){//如果沒有下一個節點則自動增加一個節點,初始值為0;nttttnextNode = new ListNode(0);nttttcurrNode.next = nextNode;nttt}nttt//下一個節點的值進行累加ntttnextNode.val ++;//累計加一ntttcurrNode.val = currNode.val%10;//更新原先的值ntt}nnttcurrNode = currNode.next;//讀取下一個節點nt}nnntreturn resL;//返回鏈表頭n};nnfunction getNodeValue(node){ntvar value = 0;ntif(node && node.val !== null){nttvalue = parseInt(node.val) || 0;nt}ntreturn value;n}nfunction hasNextNode(node){ntreturn node && node.next !== null;n}nfunction makeLink(arr){ntvar currNode = new ListNode(arr[0]);ntvar l = currNode;ntarr.forEach(function(value, index){nttif(index > 0){ntttvar newNode = new ListNode(value);ntttcurrNode.next = newNode;ntttcurrNode = currNode.next;ntt}nt});ntreturn l;n}nfunction getLinkValue(list){ntvar currNode = list;ntvar arr = [currNode.val];ntwhile(currNode.next){nttarr.push(currNode.next.val);nttcurrNode = currNode.next;nt}nntreturn arr;n}nvar l1 = makeLink([1,2,3,4]);nvar l2 = makeLink([5,6,7]);nvar res = addTwoNumbers(l1, l2);nconsole.log(getLinkValue(l1));//1,2,3,4nconsole.log(getLinkValue(l2));//5,6,7nconsole.log(getLinkValue(res));//[ 6, 8, 0, 5 ]n

講道理應該通過leetcode的才對,不知道為什麼那邊的測試用例返回下面的結果:

有知道原因的朋友請指點下。

推薦閱讀:

刷leetcode吃力正常嗎?
【LeetCode】005-最長迴文子串

TAG:LeetCode |