Insertion Sort List

题目描述

Sort a linked list using insertion sort.

解题方法

  • dummy head
  • 每当插入一个新的Node时,就用Dummy开始找它应该在的位置

Solution

/**
 * 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) {
        ListNode dummy = new ListNode(0);
        while (head != null){
            ListNode pre = dummy;
            while(pre.next != null && pre.next.val < head.val){
                pre = pre.next;
            }
            ListNode tmp = head.next;
            head.next = pre.next;
            pre.next = head;
            head = tmp;
        }
        return dummy.next;
    }
}

python的相同code过不了,囧……

Reference