C++ solution for beat 86.6%


  • 0
    C
    /**
     * Definition for singly-linked list.
     * struct ListNode {
     *     int val;
     *     ListNode *next;
     *     ListNode(int x) : val(x), next(NULL) {}
     * };
     */
    class Solution {
    public:
        ListNode* insertionSortList(ListNode* head) {
            if(head==nullptr){
                return nullptr;
            }
            ListNode* curr;
            ListNode* pre;
            curr = head->next;
            pre = head;
            while(curr!=nullptr){
                if(curr->val>=pre->val){
                    pre = curr;
                    curr = curr->next;
                    continue;
                }
                int target = curr->val;
                ListNode* tmp = head;
                pre->next = curr->next;
                if(head->val > target){
                    curr->next = head;
                    head = curr;
                }else{
                    while(tmp!=pre){
                        if(tmp->val <= target && tmp->next->val >= target){
                            ListNode* tmpNext = tmp->next;
                            tmp->next = curr;
                            curr->next = tmpNext;
                            break;
                        }else{
                            tmp = tmp->next;
                        }
                    }
                }
                curr = pre->next;
            }
            return head;
        }
    };

Log in to reply
 

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