147. Insertion Sort List(插入排序)

FreeeLinux發表於2017-02-21
Sort a linked list using insertion sort.

單連結串列的插入排序:

class Solution {
public:
    ListNode* insertionSortList(ListNode* head) {
        ListNode* new_head = NULL;
        while(head != NULL){
            ListNode* node = head;
            head = head->next;
            node->next = NULL; //這句沒有leetcode也能通過,不過還是應該加上
            insertion_sort(&new_head, node);
        }
        return new_head;
    }
    void insertion_sort(ListNode** pp, ListNode* node) {
        while(*pp != NULL && (*pp)->val < node->val)
            pp = &((*pp)->next);

        node->next = *pp;
        *pp = node;
    }
};

相關文章