Sort a linked list using insertion sort.
Example
Given 1->3->2->0->null
, return 0->1->2->3->null
.
思路也比较直接,insertion sort,要注意的就是操作linkedlist的一些问题
/** * Definition for ListNode. * public class ListNode { * int val; * ListNode next; * ListNode(int val) { * this.val = val; * this.next = null; * } * } */ public class Solution { /** * @param head: The first node of linked list. * @return: The head of linked list. */ public ListNode insertionSortList(ListNode head) { // write your code here if(head == null || head.next == null) return head; ListNode fakehead = new ListNode(0); fakehead.next = head; ListNode prev = head; ListNode curr = head.next; while(curr != null){ if(curr.val > prev.val){ prev = curr; curr = curr.next; } else{ ListNode p = fakehead; while(p != prev && p.next.val < curr.val) p = p.next; prev.next = curr.next; curr.next = p.next; p.next = curr; curr = prev.next; } } return fakehead.next; } }