https://leetcode-cn.com/problems/insertion-sort-list/description/
对链表进行插入排序。
插入排序的动画演示如上。从第一个元素开始,该链表可以被认为已经部分排序(用黑色表示)。
每次迭代时,从输入数据中移除一个元素(用红色表示),并原地将其插入到已排好序的链表中。
插入排序算法:
示例 1:
输入: 4->2->1->3 输出: 1->2->3->4
示例 2:
输入: -1->5->3->4->0 输出: -1->0->3->4->5
/** * 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) { ListNode* Head = new ListNode(0); ListNode* cur = Head->next; ListNode* next = head; ListNode* prev = Head; while (head) { next = head->next; cur = Head->next; prev = Head; while (cur && cur->val <= head->val) { prev = cur; cur = cur->next; } prev->next = head; head->next = cur; head = next; } return Head->next; } };