A music app stores a playlist as a singly linked list of ListNodes, where each val is a track's length in seconds. The user taps "Shortest first".
Write sortPlaylist(head) that sorts the list ascending by val and returns the new head. Use insertion sort: take nodes one at a time from the original list and insert each into the right place in a growing sorted list. Equal values must keep their original order.
Input: head = [4,2,1,3] Output: [1,2,3,4]
Each node is inserted into its place in the sorted part.
Input: head = [180,95,240,95] Output: [95,95,180,240]
Both 95s move to the front, in their original order.
0 <= number of nodes <= 20001 <= val <= 10^4Lists 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 #189 Insertion Sort a Linked Playlist. 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.