C++ solution using reference pointer


  • 0
    Y
    class Solution {
    public:
        ListNode* insertionSortList(ListNode* head) {
            if (!head || !head->next) return head;
            ListNode* newList = NULL;
            ListNode* p = head;
            while(p) {
                ListNode* pnext = p->next;
                insert(&newList, p);
                p = pnext;
            }
            return newList;
        }
    
        void insert(ListNode** headRef, ListNode* p) {
            ListNode** cur = headRef;
            while ((*cur) && (*cur)->val < p->val) {
                cur = &((*cur)->next);
            }
            p->next = (*cur);
            (*cur) = p;
        }
    };

Log in to reply
 

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