题目:Sort a linked list using insertion sort.
插入排序算法详解:
链接:https://www.cnblogs.com/kkun/archive/2011/11/23/2260265.html
节点类:
1 class ListNode{ 2 int val; 3 ListNode next; 4 ListNode(int x){ 5 val = x; 6 next = null; 7 } 8 }
Solution:
1 public class Solution { 2 public ListNode insertionSortList(ListNode head) { 3 if(head == null || head.next == null) return head; 4 ListNode p = head; 5 while(p!=null) { 6 ListNode temp = p; 7 ListNode min = p; 8 while (temp != null) { 9 if (temp.val < min.val) { 10 min = temp; 11 } 12 temp = temp.next; 13 } 14 int t = p.val; 15 p.val = min.val; 16 min.val = t; 17 p = p.next; 18 } 19 return head; 20 } 21 }
重点:
1)算法详解见链接
2)使用交换节点值代替交换节点,避免多使用指针的麻烦。