[Sort] [list] Leetcode147 linked list insertion sort


Ideas:
insertion algorithm of thinking is very simple, this question is relatively linked list data type, is not a convenient one move elements backward, but to find the location should be inserted relatively cumbersome, since lists only the next pointer can not be inserted quickly locate position. In front of the list and a dummy pointer to the head node, easy access and reduced subsequent judgment.

class Solution {
public:
    ListNode* insertionSortList(ListNode* head) {
        const int inf = 0x3f3f3f3f;
        if(head == NULL) return NULL;
        if(head->next == NULL) return head; 
        //构建一个空指针指向开头
        ListNode *headNULL = new ListNode(inf);
        headNULL -> next = head; 
        ListNode *cur = head->next;
        head -> next = NULL; 
        while(cur !=NULL){
            ListNode *p = headNULL;
            while(p->next != NULL && p->next->val < cur->val){ //当找到第一个大于当前值的节点时,退出循环
                p = p->next;
            }
            //此时p->next 既是第一个大于当前值的节点,p指向应插入位置的前一个节点,即要在p和p->next之间插入当前值
            ListNode *tmp = cur->next;
            cur -> next = p->next;
            p -> next = cur;
            cur = tmp;
        }
    //返回首节点
    return headNULL->next;
    }
};

Guess you like

Origin www.cnblogs.com/hhhuang/p/12026183.html