leetcode 147.对链表进行插入排序

1.题目要求:

c 复制代码
给定单个链表的头 head ,使用 插入排序 对链表进行排序,并返回 排序后链表的头 。

插入排序 算法的步骤:

插入排序是迭代的,每次只移动一个元素,直到所有元素可以形成一个有序的输出列表。
每次迭代中,插入排序只从输入数据中移除一个待排序的元素,找到它在序列中适当的位置,并将其插入。
重复直到所有输入数据插入完为止。
下面是插入排序算法的一个图形示例。部分排序的列表(黑色)最初只包含列表中的第一个元素。每次迭代时,从输入数据中删除一个元素(红色),并就地插入已排序的列表中。

对链表进行插入排序。

2.题目代码:

c 复制代码
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
 //插入排序函数:
 void insert_sort(int* arr,int length){
    for(int i = 1;i < length;i++){
        if(arr[i - 1] > arr[i]){
            int temp = arr[i];
            int j;
            for(j = i - 1;j >= 0&&temp < arr[j];j--){
                arr[j + 1] = arr[j];
            }
            arr[j + 1] = temp;
        }
    }
 }
struct ListNode* insertionSortList(struct ListNode* head) {
    int count = 0;
    struct ListNode* cur = head;
    //查到结点数目
    while(cur){
        count++;
        cur = cur->next;
    }
    //创造数组
    int* number = (int*)malloc(sizeof(int) * count);
    int j = 0;
    cur = head;
    //把链表的节点存入数组中
    while(cur){
        number[j] = cur->val;
        j++;
        cur = cur->next;
    }
    //进行插入排序
    insert_sort(number,j);
    //把排序好的数组存入链表
    cur = head;
    j = 0;
    while(cur){
        cur->val = number[j];
        j++;
        cur = cur->next;
    }
    return head;
}
相关推荐
এ᭄画画的北北41 分钟前
力扣-160.相交链表
算法·leetcode·链表
丶Darling.2 小时前
26考研 | 王道 | 数据结构 | 第八章 排序
数据结构·考研·排序算法
mit6.8244 小时前
[贪心_7] 最优除法 | 跳跃游戏 II | 加油站
数据结构·算法·leetcode
江沉晚呤时5 小时前
深入了解C# List集合及两种常见排序算法:插入排序与堆排序
windows·sql·算法·oracle·c#·排序算法·mybatis
凯子坚持 c6 小时前
深度解析之算法之分治(快排)
算法·leetcode·职场和发展
石去皿12 小时前
力扣hot100 91-100记录
算法·leetcode·职场和发展
圣保罗的大教堂13 小时前
leetcode 2799. 统计完全子数组的数目 中等
leetcode
SsummerC13 小时前
【leetcode100】组合总和Ⅳ
数据结构·python·算法·leetcode·动态规划
YuCaiH14 小时前
数组理论基础
笔记·leetcode·c·数组
2301_8076114914 小时前
77. 组合
c++·算法·leetcode·深度优先·回溯