Sort a linked list using insertion sort.
链表的插入排序
思路,递归到链表尾,然后循环插入;
1 /** 2 * Definition for singly-linked list. 3 * public class ListNode { 4 * int val; 5 * ListNode next; 6 * ListNode(int x) { val = x; } 7 * } 8 */ 9 class Solution { 10 public ListNode insertionSortList(ListNode head) { 11 if (head==null||head.next==null) 12 return head; 13 head.next = insertionSortList(head.next); 14 ListNode p = head; 15 while (p.next!=null){ 16 if (p.val>p.next.val){ 17 int tmp = p.val; 18 p.val = p.next.val; 19 p.next.val = tmp; 20 } 21 p = p.next; 22 } 23 return head; 24 } 25 }