【题目】
Sort a linked list using insertion sort.
【题意】
在链表中实现插入排序
【分析】
传统数组版本做法就是两重循环,第一重是遍历所有元素,第二重是遍历已排序部分进行插入。对链表进行插入排序的正确方法是:新建一个头节点,遍历原来的链表,对原链表的每个节点找到新链表中适合插入位置的前指针,然后执行插入操作。链表版本类似,在遍历每个元素过程中,遍历已排序部分进行插入。
【实现】
时间复杂度O(n^2)
<span style="font-size:18px;">/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode insertionSortList(ListNode head) {
if(head == null || head.next == null) return head;
ListNode newHead = new ListNode(-1);
newHead.next = head;
ListNode cur = head;
ListNode post = head.next;
while(post!=null){
if(post.val>=cur.val){
cur = cur.next;
post = post.next;
}else {
ListNode insertCur = newHead;
ListNode insertPost = newHead.next;
while(insertPost.val<post.val){
insertCur = insertPost;
insertPost = insertPost.next;
}
cur.next = post.next;
post.next = insertPost;
insertCur.next = post;
post = cur.next;
}
}
return newHead.next;
}
}</span>
别人的:
要求在链表上实现一种排序算法,这道题是指定实现插入排序。插入排序是一种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的时候的边界情况。
http://blog.csdn.net/linhuanmars/article/details/19948569
注:静态链表插入排序(List Insertion Sort)算法是直接插入排序的一个变种。它的改进目的是减少在直接插入排序中的移动次数(当然这个改进并没有降低复杂度,仍为O(n^2)),因此在原输入数据的基础上附加了一个静态链表(为了减少空间的消耗,静态链表实际上就是用等长的下标数组link来模拟的,而不需要建立一个等长的动态链结构)。该算法的缺点是:虽然减少了移动次数,但是需要增加一个等长度的link数组,所以也是用空间换取时间的做法。
http://blog.csdn.net/ljsspace/article/details/6619659
http://blog.csdn.net/linhuanmars/article/details/21133949