LeetCode: Flatten a Multilevel Doubly Linked List Solution

Naming variables is also important

Approach

Iterative way

If a node has a child:

  • point node's next to child, child's prev 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) continue
4
5 let child = node.child
6 let next = node.next
7
8 node.next = child
9 child.prev = node
10 node.child = null
11
12 while (child.next) child = child.next
13 child.next = next
14 if (next) next.prev = child
15 }
16 return head
17}

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

HoningJS

Search Posts