[LintCode] Insertion Sort List

Insertion Sort List

Sort a linked list using insertion sort.

Example

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

 

SOLUTION:

插入排序的思路就是从头开始扫过去,然后遇到比当前点小的点,就把这个点插到当前点之前。插入之后这次操作就完了,从头再扫一遍,直到扫到最后一个点位置。

代码:

/**
 * 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) {
        if (head == null){
            return head;
        }
        ListNode dummy = new ListNode(0);
        // ListNode node = dummy;
        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;
    }
}
View Code

 

posted @ 2015-11-17 10:57  Tri_tri_tri  阅读(138)  评论(0)    收藏  举报