Insertion Sort List -- LeetCode

分享一下我老师大神的人工智能教程!零基础,通俗易懂!http://blog.csdn.net/jiangjunshow

也欢迎大家转载本篇文章。分享知识,造福人民,实现我们中华民族伟大复兴!

                原题链接:  http://oj.leetcode.com/problems/insertion-sort-list/  
这道题跟 Sort List 类似,要求在链表上实现一种排序算法,这道题是指定实现插入排序。插入排序是一种O(n^2)复杂度的算法,基本想法相信大家都比较了解,就是每次循环找到一个元素在当前排好的结果中相对应的位置,然后插进去,经过n次迭代之后就得到排好序的结果了。了解了思路之后就是链表的基本操作了,搜索并进行相应的插入。时间复杂度是排序算法的O(n^2),空间复杂度是O(1)。代码如下: 
public ListNode insertionSortList(ListNode head) {    if(head == null)        return null;    ListNode helper = new ListNode(0);    ListNode pre = helper;    ListNode cur = head;    while(cur!=null)    {        ListNode next = cur.next;        pre = helper;        while(pre.next!=null && pre.next.val<=cur.val)        {            pre = pre.next;        }        cur.next = pre.next;        pre.next = cur;        cur = next;    }    return helper.next;}
这道题其实主要考察链表的基本操作,用到的小技巧也就是在 Swap Nodes in Pairs 中提到的用一个辅助指针来做表头避免处理改变head的时候的边界情况。作为基础大家还是得练习一下哈。
           

给我老师的人工智能教程打call!http://blog.csdn.net/jiangjunshow

这里写图片描述

猜你喜欢

转载自blog.csdn.net/weixin_43418664/article/details/84076644