147. Insertion Sort List

Sort a linked list using insertion sort.

============

思路:

怎么判断链表开始?   怎么判断链表结束?

定义dummy假的头节点,这样的话直接就有了链表头dummy.next

怎么将curr指向的节点插入到in指向的位置?

  四步就可以完成:ListNode *tmp = curr->next;//保存curr下一节点

          curr->next = in->next;//将curr节点接到in的下一位置,后指

          in->next = curr;//完成前指

          curr = tmp;//更新curr

代码:

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode *findLocationInsert(ListNode *head,int x){
        for(;head->next;head = head->next){
            if(head->next->val >= x) break;
        }
        return head;
    }
    ListNode *insertionSortList(ListNode* head) {
        if(head==nullptr || head->next==nullptr) return head;
        ListNode dummy(-1);
        ListNode *curr,*in;
        curr = head;
        for(;curr;){
            in = &dummy;
            in = findLocationInsert(in,curr->val);
            ListNode *tmp = curr->next;
            curr->next = in->next;
            in->next = curr;
            curr = tmp;
        }
        return dummy.next;
    }
};
原文地址:https://www.cnblogs.com/li-daphne/p/5607207.html