Insertion Sort List (LeetCode)

Question:

https://oj.leetcode.com/problems/insertion-sort-list/

 

解答:

了解insertion sort的原理。对于前面已经排好的array, 插入新的node到相应的位置。对于array可以从排好序的array从后往前比较,如果比当前值大,则该点往后挪一位。但linked list不能这么插入。

http://en.wikipedia.org/wiki/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) {
        ListNode* newHead = NULL;
        
        ListNode* curr = head;
        
        while (curr)
        {
            ListNode* next = curr->next;
            
            if (!newHead || newHead->val > curr->val)
            {
                curr->next = newHead;
                newHead = curr;
            }
            else
            {
                ListNode* newNode = newHead;

                while (1)
                {
                    if (!newNode->next || newNode->next->val > curr->val)
                    {
                        curr->next = newNode->next;
                        newNode->next = curr;
                        break;
                    }
                    
                    newNode = newNode->next;
                }
            }

            curr = next;            
        }
        
        return newHead;
    }
};

 

posted @ 2014-11-11 14:24  smileheart  阅读(112)  评论(0编辑  收藏  举报