147. 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) {
        ListNode* sortHead = new ListNode(-1);
        ListNode* cur = head;
        while(cur)
        {
           ListNode* p = sortHead;
           ListNode *pnext = cur->next; 
           while(p && p->next && p->next->val < cur->val)
           {
               p = p->next;
           }
           cur->next = p->next;
           p->next = cur;  
           cur = pnext;  
        }  
            return sortHead->next;  
    }
};


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