LeetCode: Add Two Numbers Solution
Example of using dummy head techniqueDummy head technique in linked list
Use a dummy node to refer back to head
We could also understand this dummy node as a previous node of head
1let dummy = (iter = new ListNode())23// begin iteration4iter.next = new ListNode(/* calculation for new node */)5iter = iter.next // new ref for pointer6// end iteration78return dummy.next
Approach
Use dummy head for later head reference
Iteration will finish when both pointers for 2 lists are null
The rest is handle sum and conditioning when
- sum is larger or equal than 10
- two lists are different in length
Remember to check the remainder at last
Implementation
1var addTwoNumbers = function (l1, l2) {2 let iter1 = l13 let iter2 = l24 let dummy = (iter = new ListNode())5 let remainder = 067 while (iter1 || iter2) {8 let val1 = iter1 ? iter1.val : 09 let val2 = iter2 ? iter2.val : 010 let val = val1 + val2 + remainder11 remainder = 012 if (val >= 10) {13 val -= 1014 remainder = 115 }16 iter.next = new ListNode(val)17 iter = iter.next18 iter1 = iter1 ? iter1.next : iter119 iter2 = iter2 ? iter2.next : iter220 }21 if (remainder === 1) {22 iter.next = new ListNode(1)23 }2425 return dummy.next26}
Comments
Loading comments...
Tags
leetcode
linked list
math
Apply and earn a $2,500 bonus once you're hired on your first job!
Clients from the Fortune 500 to Silicon Valley startups
Choose your own rate, get paid on time
From hourly, part-time, to full-time positions
Flexible remote working environment
A lot of open JavaScript jobs!!
Fact corner: Referred talent are 5x more likely to pass the Toptal screening process than the average applicant.
Still hesitate? Read HoningJS author's guide on dealing with Toptal interview process.