[LeetCode] Insertion Sort List

Sort a linked list using insertion sort.

Solution:

新建链表,逐个插入即可~

/**
 * 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 || head -> next == NULL) 
            return head; //0 and 1 nodes return itself
        
        ListNode *sortedHead = new ListNode(head -> val), *srcNode = head -> next;
        while(srcNode != NULL)
        {
            ListNode *preNode = NULL, *curNode = sortedHead;
             while(curNode != NULL)
            {
                if(curNode -> val < srcNode -> val)
                 {
                     preNode = curNode;
                        curNode = curNode -> next;
                }
                else
                    break;
            }
            if(preNode != NULL)
            {
                preNode -> next = new ListNode(srcNode -> val);
                preNode -> next -> next = curNode;
            }
            else
            {
                ListNode *tmp = sortedHead;
                sortedHead = new ListNode(srcNode -> val);
                sortedHead -> next = tmp;
            }
            srcNode = srcNode -> next;
        }
        
        return sortedHead;
    }
};

 

posted @ 2014-03-13 11:33  xchangcheng  阅读(299)  评论(0编辑  收藏  举报