LeetCode | Insertion Sort List(插入法排序链表)

Sort a linked list using insertion sort.

题目解析:

链表思路不难,但是指针比较麻烦,要细心才行。这道题让我调了半天,原来是一个指针赋错了,因为用的变量p和q,导致很长时间才发现……一些规则还是要注意的,变量尽量用能区分的名称。

class Solution {
public:
    ListNode *insertionSortList(ListNode *head) {
        if(head == NULL)
            return head;
        ListNode *p = head;

        while(p->next){
            if(p->next->val < p->val){
                ListNode *q = p->next;
                p->next = q->next;
                head = insertNode(head,q);
            }else
                p = p->next;
        }
        return head;
    }
    ListNode *insertNode(ListNode *head,ListNode *p){
        if(p->val < head->val){
            p->next = head;
            head = p;
        }else{
            ListNode *q = head;
            while(q->next->val < p->val)
                q = q->next;
            p->next = q->next;
            q->next = p;
        }
        return head;
    }
};

点赞