classSolution{public:ListNode*insertionSortList(ListNode*head){ListNodedummy(0);ListNode*prev=&dummy;// The last (largest) of the sorted listwhile(head){// Current inserting nodeListNode*next=head->next;// Cache next inserting nodeif(prev->val>=head->val)// `prev` >= current inserting nodeprev=&dummy;// Move `prev` to the frontwhile(prev->next&&prev->next->val<head->val)prev=prev->next;head->next=prev->next;prev->next=head;head=next;// Update current inserting node}returndummy.next;}};
classSolution{publicListNodeinsertionSortList(ListNodehead){ListNodedummy=newListNode(0);ListNodeprev=dummy;// The last (largest) of the sorted listwhile(head!=null){// Current inserting nodeListNodenext=head.next;// Cache next inserting nodeif(prev.val>=head.val)// `prev` >= current inserting nodeprev=dummy;// Move `prev` to the frontwhile(prev.next!=null&&prev.next.val<head.val)prev=prev.next;head.next=prev.next;prev.next=head;head=next;// Update current inserting node}returndummy.next;}}