My 28ms C++ solution


  • 0
    A
    class Solution {
    public:
        ListNode* insertionSortList(ListNode* head) {
            ListNode dummy(0x7fffffff), *ins = &dummy, *p = &dummy;
            dummy.next = head;
            if (!head) return 0;
            
            for (p=head; p && p->next;)
            {
                /* initialization of ins is point */
    			for (ins = ins->val<p->next->val ? ins : &dummy; ins != p; ins=ins->next)
    					if (ins->next->val > p->next->val)
    					{/* insert node */
    						ListNode *t  = ins->next;
    						ListNode *t1 = p->next->next;
    						ins->next = p->next;
    						p->next->next = t;
                        
    						p->next = t1;
    						
    						goto NEXT;   /* not increase p but check the value of p->next */
    					}
    			p = p->next;
    NEXT:		p = p;
            }
    		return dummy.next;
        }
    };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.