Insertion Sort List

题目大意:对一个链表进行插入排序


每次从头开始寻找小于等于当前数的节点,将这个数插入到节点前面。


/**
 * 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) {
       if(head == NULL || head->next == NULL) {
            return head;
        }
        ListNode *cur = head->next, *tail = head, *cmpNode = NULL, *pre = NULL;
        while(cur != NULL) {
            cmpNode = head;
            pre = NULL;
            bool hasInserted = false;
            while(cmpNode != cur) {
                if(cur->val <= cmpNode->val) {
                    tail->next = cur->next;
                    if(pre == NULL) {
                        cur->next = head;
                        head = cur;
                    } else {
                        cur->next = pre->next;
                        pre->next = cur;
                    }
                    hasInserted = true;
                    break;
                }
                pre = cmpNode;
                cmpNode = cmpNode->next;
            }
            if(hasInserted) {
                cur = tail->next;
            } else {
                tail = cur;
                cur = cur->next;
            }
        }
        return head;
    }
};


你可能感兴趣的:(leetcode)