Created
June 19, 2019 21:29
-
-
Save restart916/3d0d68e8e0e6ccb6d5f47af90dbb3527 to your computer and use it in GitHub Desktop.
20190619_leetcode_2_AddTwoNumbers
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Definition for singly-linked list. | |
* function ListNode(val) { | |
* this.val = val; | |
* this.next = null; | |
* } | |
*/ | |
/** | |
* @param {ListNode} l1 | |
* @param {ListNode} l2 | |
* @return {ListNode} | |
*/ | |
var addTwoNumbers = function(l1, l2) { | |
let head = null; | |
let tail = null; | |
let addVal = false; | |
while(1) { | |
let lVal = (l1 ? l1.val : 0); | |
let rVal = (l2 ? l2.val : 0); | |
let val = lVal + rVal + (addVal ? 1 : 0); | |
if (val >= 10) { | |
val -= 10; | |
addVal = true; | |
} else { | |
addVal = false; | |
} | |
let node = new ListNode(val); | |
if (head == null) { | |
head = node; | |
tail = node; | |
} else { | |
tail.next = node; | |
tail = node; | |
} | |
if (l1) { | |
l1 = l1.next; | |
} | |
if (l2) { | |
l2 = l2.next; | |
} | |
if (l1 == null && l2 == null) { | |
if (addVal) { | |
tail.next = new ListNode(1); | |
} | |
break; | |
} | |
} | |
return head; | |
}; |
그런데 또 생각해보니 addVal이 있어서 다음 노드에 +1 해주는 연산도 해줘야 하고 하필이면 그 다음 노드가 9라서 그럼 그 위까지 또 올라가야되? 하는 로직을 고민하다보면 위 개선사항이 그닥 편하지도 않겠네요 ㅎㅎ
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
올리고 나서 생각해보니 둘중 하나가 끝났을때 그 시점 tail.next 를 아직 남은 리스트의 당시 노드 로 연결하고 바로 break 하면 나머지 while 을 덜 돌거 같네요