代码参考来自:
https://leetcode-cn.com/problems/insertion-sort-list/comments/
public ListNode insertionSortList(ListNode head) {
ListNode dummy = new ListNode(-1);
dummy.next = head;
ListNode pre;
while (head != null && head.next != null) {
if(head.val < head.next.val) {
head = head.next;
continue;
}
pre = dummy;
while (pre.next.val < head.next.val) pre = pre.next;
ListNode curr = head.next;
head.next = curr.next;
curr.next = pre.next;
pre.next = curr;
}
return dummy.next;
}
public void printNode(ListNode head) {
while(head != null) {
System.out.print(head.val + "->");
head = head.next;
}
}
@Test
public void test() {
ListNode head = new ListNode(4);
head.next = new ListNode(2);
head.next.next= new ListNode(1);
head.next.next.next = new ListNode(3);
ListNode node = insertionSortList(head);
printNode(node);
}