链表插入排序

【插入排序】基本思想

在插入第i个数时,前i-1个数的顺序已经是排好的。只需将第i个数与前i-1个依次比较找到合适的插入位置即可。

样例

Given 1->3->2->0->null, return 0->1->2->3->null


/**
 * 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
        ListNode dummy = new ListNode(0);//dummy节点用来避免插入位置为头结点时的尴尬。这样保证插入所有位置都是相同的操作 最后只要返回dummy.next即可

        while (head != null) {
            ListNode node = dummy;
            while (node.next != null && node.next.val < head.val) {
                node = node.next;
            }
            ListNode temp = head.next;
            head.next = node.next;
            node.next = head;
            head = temp;
        }
        return dummy.next;
    }
}

你可能感兴趣的:(lintcode,记录-easy,排序)