【LeetCode OJ】Insertion Sort List

Posted on 2014-03-13 03:05  卢泽尔  阅读(264)  评论(0)    收藏  举报

Problem:

Sort a linked list using insertion sort.

The node of the linked list is defined as:

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */

 


The insertion sorting is one of the simpleset sorting algorithms, which is of O(n^2) time in the worst case.

The key of the insertion sorting is how to keep track of the "sorted" part and "unsorted" part. For sorting an array we just need to keep track the last index of the sorted part; for sorting a linked list, it becomes much complex since you need maintain two pointers, one points to the last sorted element and the other one points to the first unsorted element. Each time, we insert the first unsorted element into the sorted linked list and update the two pointers.

The C++ code is as follows:

/**
 * 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 == NULL) return head;
        ListNode *sorted_tail = head;
        ListNode *unsorted_head = sorted_tail->next;
        ListNode *prev = NULL;
        ListNode *p = NULL;
        while (unsorted_head != NULL) {
            // Find the position to insert the element after the tail
            p = head;
            while (p->val <= unsorted_head->val && p != unsorted_head) {
                prev = p;
                p=p->next;
            }
            // Insert
            if (p == unsorted_head) sorted_tail = sorted_tail->next;
            else {
                sorted_tail->next = unsorted_head->next;
                unsorted_head->next = p;
                if (p == head) head = unsorted_head;
                else prev->next = unsorted_head;
            }
            unsorted_head = sorted_tail->next;
        }
        return head;
    }
};