给定单个链表的头 head ,使用 插入排序 对链表进行排序,并返回 排序后链表的头 。
插入排序 算法的步骤:
- 插入排序是迭代的,每次只移动一个元素,直到所有元素可以形成一个有序的输出列表。
- 每次迭代中,插入排序只从输入数据中移除一个待排序的元素,找到它在序列中适当的位置,并将其插入。
- 重复直到所有输入数据插入完为止。
部分排序的列表最初只包含列表中的第一个元素。每次迭代时,从输入数据中选择一个元素,并就地插入已排序的列表中。
code
#include <iostream>
#include <vector>
using namespace std;
struct ListNode {
int val;
ListNode *next;
ListNode() : val(0), next(nullptr) {}
ListNode(int x) : val(x), next(nullptr) {}
ListNode(int x, ListNode *next) : val(x), next(next) {}
};
class Solution {
public:
ListNode* insertionSortList(ListNode* head) {
ListNode* cur = head;//插入排序需要有一个遍历的过程,cur为遍历的指针
ListNode* dummy = new ListNode(0);// dummy为排序后的链表的虚拟头节点
while(cur){
ListNode* pre = dummy;
ListNode* next = cur->next;
while(pre->next && pre->next->val <= cur->val){
pre = pre->next;
}
//将cur插入到dummy链中
cur->next = pre->next;// 链表中等号右边的值为要保存的值
pre->next = cur;
//继续移动原始链条上的指针
cur = next;
}
return dummy->next;
}
};
int main()
{
cout<<"Hello World"<<endl;
Solution mysolution;
//构建输入数据
vector<int> v ={4,2,1,3};
ListNode *head = new ListNode(v[0]);
ListNode *cur=head,*tmp;
for(int i=1;i<v.size();i++){
tmp = new ListNode(v[i]);
cur->next = tmp;
cur = tmp;
}
//处理
ListNode* res = mysolution.insertionSortList(head);
//结果输出
while(res != nullptr){
cout<< res->val <<endl;
res = res->next;
}
return 0;
}
CG
- 数组方法
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
int cmpfunc (const void * a, const void * b) /*排序函数的比较函数*/
{
return ( *(int*)a - *(int*)b );
}
struct ListNode* insertionSortList(struct ListNode* head){
struct ListNode *p1 = head;
int length = 0;
while(p1 != NULL){
length++;
p1 = p1->next;
}
if(length <= 1)return head;
else{
int array[length];
p1 = head;
for(int i = 0; i < length; i++){
array[i] = p1->val;
p1 = p1->next;
}
qsort(array, length, sizeof(int), cmpfunc);
p1 = head;
for(int i = 0; i < length; i++){
p1->val = array[i];
p1 = p1->next;
}
return head;
}
}
作者:yuan9931
链接:https://leetcode.cn/problems/insertion-sort-list/solution/cai-niao-li-yong-shu-zu-pai-xu-8ms-by-yuan9931/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。