题目
插入排序是迭代的,每次只移动一个元素,直到所有元素可以形成一个有序的输出列表。
每次迭代中,插入排序只从输入数据中移除一个待排序的元素,找到它在序列中适当的位置,并将其插入。
重复直到所有输入数据插入完为止。
实现
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
/*
类似于数组的插入排序,不同点在于数组中是从后往前遍历,链表需要从前往后遍历;数组中两元素做交换,链表中是插入和删除
1.设置虚拟头节点
2.比较两个节点compare 和 current,需要保留current的pre,next;compare的pre节点以便进行current的删除和插入
3.两个节点都涉及到前置节点,所以循环条件采用前置节点
*/
class Solution {
public:
ListNode* insertionSortList(ListNode* head) {
ListNode* pre = new ListNode(0);
pre->next = head;
ListNode* cur_pre = head;
while (cur_pre != NULL && cur_pre->next != NULL) {
//判断cur_pre怎么变化
int flag = 0;
ListNode* cur = cur_pre->next;
//当前节点的后置节点
ListNode* cur_post = cur->next;
ListNode* com_pre = pre;
while (com_pre != NULL && com_pre != cur_pre) {
ListNode* com = com_pre->next;
if (com->val <= cur->val) {
com_pre = com_pre->next;
} else {
cur->next = com;
com_pre->next = cur;
//这个时候cur_pre不需要移动,flag设置为1
flag = 1;
cur_pre->next = cur_post;
break;
}
}
//flag为0,需要移动cur_pre
if (flag == 0) {
cur_pre = cur_pre->next;
}
}
return pre->next;
}
};