A build server keeps pending jobs in a singly linked list of ListNodes. Each val is a job's priority number, and lower numbers run first. The queue can hold tens of thousands of jobs, so an O(n²) sort is too slow.
Write sortQueue(head) that sorts the list ascending by val in O(n log n) time and returns the new head. Jobs with equal priority must keep their original order.
Input: head = [4,2,1,3] Output: [1,2,3,4]
Split into 4, 2 and 1, 3, sort each, then merge.
Input: head = [-1,5,3,4,0] Output: [-1,0,3,4,5]
Negative priorities run first.
0 <= number of nodes <= 50000-10^5 <= val <= 10^5Lists are written as arrays here, like [1, 2, 3]. Your function works with ListNode objects, each with val and next.
Run tries your code on the examples. Submit runs every test, including hidden edge cases, and solves the problem when they all pass.
Ctrl + Enter runs, Ctrl + Shift + Enter submits (⌘ on a Mac).
I'm here to help with #190 Merge Sort a Linked Job Queue. I give hints, never the solution, so you get to solve it yourself. Ask for a hint, select code to ask about it, or press Ask Tuto why on a failing test.
Your first 3 answers need no account. for free to keep asking.