Insertion Sort List

用插入排序对链表排序

您在真实的面试中是否遇到过这个题?  
Yes
样例

Given 1->3->2->0->null, return 0->1->2->3->null

/**
 * Definition of ListNode
 * class ListNode {
 * public:
 *     int val;
 *     ListNode *next;
 *     ListNode(int val) {
 *         this->val = val;
 *         this->next = NULL;
 *     }
 * }
 */
class Solution {
public:
    /**
     * @param head: The first node of linked list.
     * @return: The head of linked list.
     */
    ListNode *insertionSortList(ListNode *head) {
        // write your code here
        if(head==NULL||head->next==NULL) return head;
        ListNode *dummy=new ListNode(-1);
        dummy->next=head;
        ListNode* pre=head;
        ListNode *cur=head->next;
        while(cur){
            if(cur->val>=pre->val){
                pre=pre->next;
                
            }else{
                pre->next=cur->next;
                ListNode *restart=dummy;
                while(cur->val>=restart->next->val){
                    restart=restart->next;
                }
                cur->next=restart->next;
                restart->next=cur;
            }
            cur=pre->next;
        }
        return dummy->next;
    }
};


你可能感兴趣的:(Insertion Sort List)