Insertion Sort List
Sort a linked list using insertion sort.
解析:使用插入排序对链表节点进行排序
代码:
/**
* 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 dummy = new ListNode(0);
ListNode pre = dummy;
while(head!=null)
{
while(pre.next!=null&&head.val>=pre.next.val)
{
pre = pre.next;
}
ListNode insert = new ListNode(head.val);
insert.next = pre.next;
pre.next = insert;
head = head.next;
pre = dummy;
}
return dummy.next;
}
}