链表的插入排序实现原理很简单,就是一个元素一个元素的从原链表中取出来,然后按顺序插入到新链表中,时间复杂度为O(n2),是一种效率并不是很高的算法,但是空间复杂度为O(1),以高时间复杂度换取了低空间复杂度。代码如下:
package com.zhumq.lianxi;
public class InsertionSortList {
public class ListNode{
public int val;
public ListNode next;
public ListNode(int val) {
this.val = val;
}
}
public ListNode insertionSortList(ListNode head) {
//保存排序后链表
ListNode dummy = new ListNode(Integer.MIN_VALUE);
//dummy.next = head;
for (ListNode cur = head; cur != null;) {
//寻找插入位置
ListNode pos = findInsertPos(dummy, cur.val);
ListNode tmp = cur.next;
cur.next = pos.next;
pos.next = cur;
cur = tmp;
}
return dummy.next;
}
ListNode findInsertPos(ListNode head, int x) {
ListNode pre = null;
for (ListNode cur = head; cur != null && cur.val <= x;pre = cur, cur = cur.next);
return pre;
}
}