LeetCode题解:Insertion Sort List


Insertion Sort List


Sort a linked list using insertion sort.
思路:
标准的插入排序。就是考察一下链表的操作而已。
题解:
/**
 * 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* inserted = head;
    
        while(inserted->next != nullptr)
        {
            // find the position of insertion
            ListNode* i = head;
    
            // is insertion on the head?
            if (i->val >= inserted->next->val)
                i = inserted->next->next,
                  inserted->next->next = head,
                  head = inserted->next,
                  inserted->next = i;
            else
            {
                // make i locate at the node prior to the insertion
                while(! (i->next->val >= inserted->next->val))
                    i = i->next;
    
                if (i != inserted)
                {
                    ListNode* tmp = inserted->next;
                    // insert
                    inserted->next = tmp->next;
                    tmp->next = i->next;
                    i->next = tmp;
                }
                else
                    inserted=inserted->next;
            }
        }
    
        return head;
    }
};


你可能感兴趣的:(数据结构和算法)