Flattening a Linked List

hard

You are given the head of a linked list where every node has two pointers: next (to the next node in the top-level list) and bottom (to a vertical sub-list). Every bottom sub-list is sorted, and the top-level list is sorted by next as well.

Flatten the structure into a single sorted list linked entirely through the bottom pointer, and return its head.

Input encoding: each line is one vertical sub-list — its first value is the top-level node, the rest hang off it via bottom; consecutive lines are joined via next. The judge reads your result by following bottom from the returned head.

Constraints

- The number of nodes is in the range [0, 10^4] - Each vertical sub-list is sorted in non-decreasing order - 1 <= Node.val <= 10^5

Solve this problem →