Sort a linked list using insertion sort.
使用插入排序对链表排序。
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode insertionSortList(ListNode head) {
//使用头插法来进行直接插入排序
if(head == null || head.next == null){
return head;
}
//创建一个新的链表
ListNode t = new ListNode(head.val);
t.next = null;
head = head.next;
while(head != null){
//要插入的节点
ListNode node = new ListNode(head.val);
node.next = null;
//保持返回链表的头结点不变
ListNode p = t;
ListNode p_before = t;
while(p.val < head.val && p.next != null){
//找到插入点所在的插入位置
p_before = p;
p = p.next;
}
if(p.val < head.val){
p.next = node;
}else{
//分为两种情况,一直是直接在头插入,另一种是在中间插入
if(p_before == p){
//头结点插入
node.next = t;
t = node;
}else{
//中间插入
node.next = p_before.next;
p_before.next = node;
}
}
head = head.next;
}
return t;
}
}