LeetCode: Flatten a Multilevel Doubly Linked List Solution
Naming variables is also importantApproach
Iterative way
If a node has a child:
- point node's
next
to child, child'sprev
to node - iterate child to its tail, then point tail's next to original node's next, original node's next's prev to tail
But I think variables naming for better readability in this task is important also, for our future self
Implementation
1var flatten = function (head) {2 for (let node = head; node; node = node.next) {3 if (!node.child) continue45 let child = node.child6 let next = node.next78 node.next = child9 child.prev = node10 node.child = null1112 while (child.next) child = child.next13 child.next = next14 if (next) next.prev = child15 }16 return head17}
Comments
Loading comments...
Tags
leetcode
linked list
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.
Next Post
LeetCode: Rotate List
Should draw for better imagination of how it works
Previous Post
LeetCode: Add Two Numbers
Example of using dummy head technique