147. Insertion Sort List

195 篇文章 0 订阅
问题描述

Sort a linked list using insertion sort.

题目链接:


思路分析

用插入排序对一个链表进行排序。

插入排序就是对于新的元素,将它插入到已排序的元素的合适位置。如果是在数组中,还需要移动元素,但是对于链表就没有这个必要了,所以非常适合链表。

我们设置一个新的头new_head,cur = head表示之前的结点已经排序,和一个寻找合适位置的pre结点。然后以cur为基准进行循环,对于大于cur->val的就保持原位置;小于cur->val的就要找到合适的位置链接上。用一个while找到合适的位置,然后用temp保存pre->next,重置pre->next,将cur->next从原序列里删除,然后将pre->next重新连接上,插删连三步。最后将pre重置即可。

代码
/**
 * 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 || !head->next)
            return head;
        ListNode* new_head = new ListNode(0);
        new_head->next = head;
        ListNode* pre = new_head;
        ListNode* cur = head;
        while (cur){
            if (cur->next && cur->next->val < cur->val){
                //find little node and put it to right place
                while (pre->next && pre->next->val < cur->next->val)
                    pre = pre->next;
                //pust cur->next to pre->next and keep the list
                ListNode* temp = pre->next;
                pre->next = cur->next;
                cur->next = cur->next->next;//take cur->next away
                pre->next->next = temp;
                //move pre back to the head;
                pre = new_head;
            }
            else
                cur = cur->next;
        }

        return new_head->next;

    }
};

时间复杂度: O(n2) O ( n 2 )
空间复杂度: O(1) O ( 1 )


反思

链表题思路要清晰。

Java实现插入排序可以使用以下代码: private static void insertionSort(int[] arr) { int len = arr.length; int temp, j; for (int i = 1; i < len; i++) { temp = arr[i]; j = i - 1; while (j >= 0 && arr[j] > temp) { arr[j + 1] = arr[j]; j--; } arr[j + 1] = temp; } System.out.println(Arrays.toString(arr)); } 这段代码使用了插入排序的算法。它首先将数组分为已排序和未排序两部分,然后从未排序部分选择一个元素,将其插入到已排序部分的正确位置。在每次迭代中,将当前元素与已排序部分的元素进行比较,如果当前元素比已排序部分的元素小,则将已排序部分的元素向后移动,然后将当前元素插入到正确的位置。 以上是一种基本的插入排序算法实现,通过比较数组中的相邻元素进行排序。这种算法的时间复杂度为O(n^2),其中n是数组的长度。可以根据实际情况进行性能优化,如使用二分查找来减少比较的次数,或者使用其他排序算法来替代插入排序。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* *3* [今日算法解读之Java版插入排序(Insertion Sort)](https://blog.csdn.net/qq_42349895/article/details/117304461)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 100%"] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值