Created
June 29, 2019 09:39
-
-
Save restart916/af7491ebb11a384b61a2083fba14e1bc to your computer and use it in GitHub Desktop.
20190629_leetcode_445_AddTwoNumbersII
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 l1_point = l1 | |
let l2_point = l2 | |
let l1_count = 1, l2_count = 1 | |
while (l1_point.next) { | |
l1_count++ | |
l1_point = l1_point.next | |
} | |
while (l2_point.next) { | |
l2_count++ | |
l2_point = l2_point.next | |
} | |
console.log(l1_count, l2_count) | |
console.log(l1_point.val, l2_point.val) | |
let longer = l1_count > l2_count ? l1 : l2 | |
let shorter = longer === l1 ? l2 : l1 | |
let diff = Math.abs(l1_count - l2_count) | |
let total_length = Math.max(l1_count, l2_count) | |
console.log(longer.val, shorter.val, diff) | |
let result_node = null, result_head = null | |
let add_val = 0, sum_val = 0 | |
while (total_length--) { | |
if (diff) { | |
sum_val = longer.val + add_val | |
longer = longer.next | |
diff-- | |
} else { | |
sum_val = longer.val + shorter.val | |
longer = longer.next | |
shorter = shorter.next | |
} | |
if (sum_val > 9) { | |
sum_val -= 10 | |
add_val = 1 | |
} else { | |
add_val = 0 | |
} | |
new_node = new ListNode(sum_val) | |
if (add_val) { | |
add_node = result_node | |
running = true | |
while(running) { | |
if (add_node) { | |
add_node.val += 1 | |
if (add_node.val >= 10) { | |
add_node.val = 0 | |
find_node = result_head | |
while(add_node != find_node.next) { | |
find_node = find_node.next | |
if (find_node == null) { | |
new_head = new ListNode(1) | |
new_head.next = result_head | |
result_head = new_head | |
running = false | |
break; | |
} | |
} | |
add_node = find_node | |
} else { | |
running = false | |
} | |
} else { | |
new_head = new ListNode(1) | |
new_head.next = result_head | |
result_head = new_head | |
result_node = new_head | |
running = false | |
} | |
} | |
} | |
if (result_node) { | |
result_node.next = new_node | |
result_node = result_node.next | |
} else { | |
result_node = new_node | |
result_head = new_node | |
} | |
} | |
return result_head | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
일단 혼이 나간상태로 풀었네요 자잘한 조건들이 많아서 막 뭐가 덕지덕지.. ㅎㅎ